RSS Banner


Session handling functions

Posted by: admin  /  Category: PHP

Introduction

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

If you are familiar with the session management of PHPLIB, you will notice that some concepts are similar to PHP’s session support.

A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Caution
If you do turn on session.auto_start then you cannot put objects into your sessions since the class definition has to be loaded before starting the session in order to recreate the objects in your session.

All registered variables are serialized after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.

Note: Session handling was added in PHP 4.0.

Note: Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function.

Sessions and security

The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session. You need to take additional measures to actively protect the integrity of the session, depending on the value associated with it.

Assess the importance of the data carried by your sessions and deploy addditional protections — this usually comes at a price, reduced convenience for the user. For example, if you want to protect users from simple social engineering tactics, you need to enable session.use_only_cookies. In that case, cookies must be enabled unconditionally on the user side, or sessions will not work.

There are several ways to leak an existing session id to third parties. A leaked session id enables the third party to access all resources which are associated with a specific id. First, URLs carrying session ids. If you link to an external site, the URL including the session id might be stored in the external site’s referrer logs. Second, a more active attacker might listen to your network traffic. If it is not encrypted, session ids will flow in plain text over the network. The solution here is to implement SSL on your server and make it mandatory for users.

Requirements

No external libraries are needed to build this extension.

Note: Optionally you can use shared memory allocation (mm), developed by Ralf S. Engelschall, for session storage. You have to download mm and install it. This option is not available for Windows platforms. Note that the session storage module for mm does not guarantee that concurrent accesses to the same session are properly locked. It might be more appropiate to use a shared memory based filesystem (such as tmpfs on Solaris/Linux, or /dev/md on BSD) to store sessions in files, because they are properly locked.

Installation

Session support is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the –disable-session option to configure. To use shared memory allocation (mm) for session storage configure PHP –with-mm[=DIR] .

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

Runtime Configuration

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

Table 1. Session configuration options

Name Default Changeable
session.save_path “/tmp” PHP_INI_ALL
session.name “PHPSESSID” PHP_INI_ALL
session.save_handler “files” PHP_INI_ALL
session.auto_start “0″ PHP_INI_ALL
session.gc_probability “1″ PHP_INI_ALL
session.gc_maxlifetime “1440″ PHP_INI_ALL
session.serialize_handler “php” PHP_INI_ALL
session.cookie_lifetime “0″ PHP_INI_ALL
session.cookie_path “/” PHP_INI_ALL
session.cookie_domain “” PHP_INI_ALL
session.cookie_secure “” PHP_INI_ALL
session.use_cookies “1″ PHP_INI_ALL
session.use_only_cookies “0″ PHP_INI_ALL
session.referer_check “” PHP_INI_ALL
session.entropy_file “” PHP_INI_ALL
session.entropy_length “0″ PHP_INI_ALL
session.cache_limiter “nocache” PHP_INI_ALL
session.cache_expire “180″ PHP_INI_ALL
session.use_trans_sid “0″ PHP_INI_SYSTEM|PHP_INI_PERDIR
url_rewriter.tags “a=href,area=href,frame=src,input=src,form=fakeentry” PHP_INI_ALL

For further details and definition of the PHP_INI_* constants see ini_set().

session.save_handler  string

session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. See also session_set_save_handler().
session.save_path string

session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. Defaults to /tmp. If session.save_path’s path depth is more than 2, garbage collection will not be performed. See also session_save_path().

Note:  Windows users have to change this variable in order to use PHP’s session functions. Make sure to specify a valid path, e.g.: c:/temp.

session.name string

session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name().
session.auto_start boolean

session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).
session.serialize_handler string

session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. Currently, a PHP internal format (name php) and WDDX is supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php.
session.gc_probability integer

session.gc_probability specifies the probability that the gc (garbage collection) routine is started on each request in percent. Defaults to 1.
session.gc_maxlifetime integer

session.gc_maxlifetime specifies the number of seconds after which data will be seen as ‘garbage’ and cleaned up.

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other fs where atime tracking is not available.

session.referer_check string

session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.
session.entropy_file string

session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems.
session.entropy_length integer

session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 0 (disabled).
session.use_cookies boolean

session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).
session.use_only_cookies boolean

session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Defaults to 0 (disabled, for backward compatibility). Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0.
session.cookie_lifetime integer

session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means “until the browser is closed.” Defaults to 0.See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_path string

session.cookie_path specifies path to set in session_cookie. Defaults to /.See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_domain string

session.cookie_domain specifies the domain to set in session_cookie. Default is none at all. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_secure boolean

session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. This setting was added in PHP 4.0.4. See also session_get_cookie_params() and session_set_cookie_params().
session.cache_limiter string

session.cache_limiter specifies cache control method to use for session pages (none/nocache/private/private_no_expire/public). Defaults to nocache. See also session_cache_limiter().
session.cache_expire integer

session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. See also session_cache_expire().
session.use_trans_sid boolean

session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled).

Note: For PHP 4.1.2 or less, it is enabled by compiling with –enable-trans-sid. From PHP 4.2.0, trans-sid feature is always compiled.

URL based session management has additional security risks compared to cookie based session management. Users may send an URL that contains an active session ID to their friends by email or users may save an URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.

url_rewriter.tags string

url_rewriter.tags specifies which html tags are rewritten to include session id if transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form=fakeentry,fieldset=

Note: If you want XHTML conformity, remove the form entry and use the <fieldset> tags around your form fields.

The track_vars and register_globals configuration settings influence how the session variables get stored and restored.

Note: As of PHP 4.0.3, track_vars is always turned on.

Resource Types

This extension has no resource types defined.

Predefined Constants

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

SID (string)
Constant containing the session name and session ID in the form of “name=ID”.

Examples

Note: As of PHP 4.1.0, $_SESSION is available as a global variable just like $_POST, $_GET, $_REQUEST and so on. Unlike $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, you do not need to use the global keyword for $_SESSION. Please note that this documentation has been changed to use $_SESSION everywhere. You can substitute $HTTP_SESSION_VARS for $_SESSION, if you prefer the former. Also note that you must start your session using session_start() before use of $_SESSION becomes available.

The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.

If register_globals is disabled, only members of the global associative array $_SESSION can be registered as session variables. The restored session variables will only be available in the array $_SESSION.

Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for improved security and code readablity. With $_SESSION, there is no need to use the session_register(), session_unregister(), session_is_registered() functions. Session variables are accessible like any other variables.

Example 1. Registering a variable with $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Example 2. Unregistering a variable with $_SESSION and register_globals disabled.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>
Example 3. Unregistering a variable with register_globals enabled, after registering it using $_SESSION.

<?php
session_start();
// With PHP 4.3 and later, you can also simply use the prior example.
session_unregister('count');
?>

If register_globals is enabled, then each global variable can be registered as session variable. Upon a restart of a session, these variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users need to register variables with session_register() function. You can avoid this by simply setting entries in $_SESSION.

Caution
If you are using $_SESSION and disable register_globals, do not use session_register(), session_is_registered() and session_unregister(), if your scripts shall work in PHP 4.2 and earlier. You can use these functions in 4.3 and later.

If you enable register_globals, session_unregister() should be used since session variables are registered as global variables when session data is deserialized. Disabling register_globals is recommended for both security and performance reasons.

Example 4. Registering a variable with register_globals enabled

<?php
if (!session_is_registered('count')) {
session_register("count");
$count = 0;
}
else {
$count++;
}
?>

If register_globals is enabled, then the global variables and the $_SESSION entries will automatically reference the same values which were registered in the prior session instance.

There is a defect in PHP 4.2.3 and earlier. If you register a new session variable by using session_register(), the entry in the global scope and the $_SESSION entry will not reference the same value until the next session_start(). I.e. a modification to the newly registered global variable will not be reflected by the $_SESSION entry. This has been corrected in PHP 4.3.

Passing the Session ID

There are two methods to propagate a session id:

  • Cookies
  • URL parameter

The session module supports both methods. Cookies are optimal, but because they are not always available, we also provide an alternative way. The second method embeds the session id directly into URLs.

PHP is capable of transforming links transparently. Unless you are using PHP 4.2 or later, you need to enable it manually when building PHP. Under UNIX, pass –enable-trans-sid to configure. If this build option and the run-time option session.use_trans_sid are enabled, relative URIs will be changed to contain the session id automatically.

Note: The arg_separator.output php.ini directive allows to customize the argument seperator. For full XHTML conformance, specify &amp; there.

Alternatively, you can use the constant SID which is always defined. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

Example 5. Counting the number of hits of a single user

<?php
if (!session_is_registered('count')) {
session_register('count');
$count = 1;
}
else {
$count++;
}
?>

Hello visitor, you have seen this page <?php echo $count; ?> times.<p>

To continue, <A HREF="nextpage.php?<?php echo strip_tags (SID)?>">click here</A>

The strip_tags() is used when printing the SID in order to prevent XSS related attacks.

Printing the SID, like shown above, is not necessary if –enable-trans-sid was used to compile PHP.

Note: Non-relative URLs are assumed to point to external sites and hence don’t append the SID, as it would be a security risk to leak the SID to a different server.

Custom Session Handlers

To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions.

Table of Contents
session_cache_expire — Return current cache expire
session_cache_limiter — Get and/or set the current cache limiter
session_decode — Decodes session data from a string
session_destroy — Destroys all data registered to a session
session_encode –  Encodes the current session data as a string
session_get_cookie_params –  Get the session cookie parameters
session_id — Get and/or set the current session id
session_is_registered –  Find out whether a global variable is registered in a session
session_module_name — Get and/or set the current session module
session_name — Get and/or set the current session name
session_readonly — Begin session - reinitializes frozen variables, but no writeback on request end
session_register –  Register one or more global variables with the current session
session_save_path — Get and/or set the current session save path
session_set_cookie_params –  Set the session cookie parameters
session_set_save_handler –  Sets user-level session storage functions
session_start — Initialize session data
session_unregister –  Unregister a global variable from the current session
session_unset –  Free all session variables
session_write_close — Write session data and end session

Shared Memory Functions

Posted by: admin  /  Category: PHP

Introduction

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete UNIX shared memory segments. These functions will not typically work on Windows, as it does not support shared memory. As of Windows 2000 though, enabling the php_shmop.dll in your php.ini will enable this functionality though.

Note: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.

Requirements

No external libraries are needed to build this extension.

Installation

To use shmop you will need to compile PHP with the –enable-shmop parameter in your configure line.

Runtime Configuration

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

Resource Types

Predefined Constants

This extension has no constants defined.

Examples

Example 1. Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id if 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);

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

Shockwave Flash functions

Posted by: admin  /  Category: PHP

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.

Requirements

You need the libswf library to compile PHP with support for this extension. You can download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash.

Installation

Once you have libswf all you need to do is to configure –with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.

Runtime Configuration

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

Resource Types

This extension has no resource types defined.

Predefined Constants

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

MOD_COLOR (integer)

MOD_MATRIX (integer)

TYPE_PUSHBUTTON (integer)

TYPE_MENUBUTTON (integer)

BSHitTest (float)

BSDown (float)

BSOver (float)

BSUp (float)

OverDowntoIdle (integer)

IdletoOverDown (integer)

OutDowntoIdle (integer)

OutDowntoOverDown (integer)

OverDowntoOutDown (integer)

OverUptoOverDown (integer)

OverUptoIdle (integer)

IdletoOverUp (integer)

ButtonEnter (integer)

ButtonExit (integer)

MenuEnter (integer)

MenuExit (integer)

Examples

Once you’ve successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

Example 1. SWF example

<?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 ();
?>
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 foward 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 –  The height in pixels of a capital A and a lowercase x
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

SNMP functions

Posted by: admin  /  Category: PHP

Requirements

In order to use the SNMP functions on Unix you need to install the UCD SNMP package. On Windows these functions are only available on NT and not on Win95/98.

Installation

Important: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:

#define NO_ZEROLENGTH_COMMUNITY 1

Now compile PHP –with-snmp[=DIR].

If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the –enable-ucd-snmp-hack switch which will work around the misfeature.

The Windows distribution contains support files for SNMP in the mibs directory. This directory should be moved to DRIVE:\usr\mibs, where DRIVE must be replaced with the driveletter where PHP is installed on, e.g.: c:\usr\mibs.

Runtime Configuration

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

Resource Types

Predefined Constants

This extension has no constants defined.

Table of Contents
snmp_get_quick_print – Fetch the current value of the UCD library’s quick_print setting
snmp_set_quick_print – Set the value of quick_print within the UCD SNMP library
snmpget – Fetch an SNMP object
snmprealwalk –  Return all objects including their respective object ID within the specified one
snmpset – Set an SNMP object
snmpwalk – Fetch all the SNMP objects from an agent
snmpwalkoid – Query for a tree of information about a network entity

Socket functions

Posted by: admin  /  Category: PHP

Introduction

The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.

For a more generic client-side socket interface, see stream_socket_client(), stream_socket_server(), fsockopen(), and pfsockopen().

When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.

Those unfamiliar with socket programming can find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP. The UNIX Socket FAQ might be a good start.

This extension is EXPERIMENTAL. The behaviour of this extension — including the names of its functions and anything else documented about this extension — may change without notice in a future release of PHP. Use this extension at your own risk

Requirements

No external libraries are needed to build this extension.

Installation

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the –enable-sockets option to configure.

Note: IPv6 Support was added with PHP 5.0 .

Runtime Configuration

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

Resource Types

This extension has no resource types defined.

Predefined Constants

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

AF_UNIX (integer)

AF_INET (integer)

AF_INET6 (integer)

SOCK_STREAM (integer)

SOCK_DGRAM (integer)

SOCK_RAW (integer)

SOCK_SEQPACKET (integer)

SOCK_RDM (integer)

MSG_OOB (integer)

MSG_WAITALL (integer)

MSG_PEEK (integer)

MSG_DONTROUTE (integer)

SO_DEBUG (integer)

SO_REUSEADDR (integer)

SO_KEEPALIVE (integer)

SO_DONTROUTE (integer)

SO_LINGER (integer)

SO_BROADCAST (integer)

SO_OOBINLINE (integer)

SO_SNDBUF (integer)

SO_RCVBUF (integer)

SO_SNDLOWAT (integer)

SO_RCVLOWAT (integer)

SO_SNDTIMEO (integer)

SO_RCVTIMEO (integer)

SO_TYPE (integer)

SO_ERROR (integer)

SOL_SOCKET (integer)

PHP_NORMAL_READ (integer)

PHP_BINARY_READ (integer)

SOL_TCP (integer)

SOL_UDP (integer)

Socket Errors

The socket extension was written to provide a useable interface to the powerful BSD sockets. Care has been taken that the functions work equally well on Win32 and Unix implementations. Almost all of the sockets functions may fail under certain conditions and therefore emit an E_WARNING message describing the error. Sometimes this doesn’t happen to the desire of the developer. For example the function socket_read() may suddenly emit an E_WARNING message because the connection broke unexpectedly. It’s common to suppress the warning with the @-operator and catch the error code within the application with the socket_last_error() function. You may call the socket_strerror() function with this error code to retrieve a string describing the error. See their description for more information.

Note: The E_WARNING messages generated by the socket extension are in english though the retrieved error message will appear depending on the current locale (LC_MESSAGES):

Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet

Examples

Example 1. Socket example: Simple TCP/IP server

This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter ‘quit’.

#!/usr/local/bin/php -q
<?php
error_reporting (E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit (0);

/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush ();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 0) {
echo "socket_create() failed: reason: " . socket_strerror ($sock) . "\n";
}

if (($ret = socket_bind ($sock, $address, $port)) < 0) {
echo "socket_bind() failed: reason: " . socket_strerror ($ret) . "\n";
}

if (($ret = socket_listen ($sock, 5)) < 0) {
echo "socket_listen() failed: reason: " . socket_strerror ($ret) . "\n";
}

do {
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror ($msgsock) . "\n";
break;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));

do {
if (FALSE === ($buf = socket_read ($msgsock, 2048))) {
echo "socket_read() failed: reason: " . socket_strerror ($ret) . "\n";
break 2;
}
if (!$buf = trim ($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close ($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write ($msgsock, $talkback, strlen ($talkback));
echo "$buf\n";
} while (true);
socket_close ($msgsock);
} while (true);

socket_close ($sock);
?>
Example 2. Socket example: Simple TCP/IP client

This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.

<?php
error_reporting (E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname ('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname ('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create (AF_INET, SOCK_STREAM, 0);
if ($socket < 0) {
echo "socket_create() failed: reason: " . socket_strerror ($socket) . "\n";
} else {
echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect ($socket, $address, $service_port);
if ($result < 0) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
} else {
echo "OK.\n";
}

$in = "HEAD / HTTP/1.0\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write ($socket, $in, strlen ($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read ($socket, 2048)) {
echo $out;
}

echo "Closing socket...";
socket_close ($socket);
echo "OK.\n\n";
?>
Table of Contents
socket_accept — Accepts a connection on a socket
socket_bind — Binds a name to a socket
socket_clear_error — Clears the error on the socket or the last error code
socket_close — Closes a socket resource
socket_connect — Initiates a connection on a socket
socket_create_listen — Opens a socket on port to accept connections
socket_create_pair — Creates a pair of indistinguishable sockets and stores them in fds.
socket_create — Create a socket (endpoint for communication)
socket_get_option — Gets socket options for the socket
socket_getpeername –  Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.
socket_getsockname –  Queries the local side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.
socket_iovec_add — Adds a new vector to the scatter/gather array
socket_iovec_alloc — …]) Builds a ’struct iovec’ for use with sendmsg, recvmsg, writev, and readv
socket_iovec_delete — Deletes a vector from an array of vectors
socket_iovec_fetch — Returns the data held in the iovec specified by iovec_id[iovec_position]
socket_iovec_free — Frees the iovec specified by iovec_id
socket_iovec_set — Sets the data held in iovec_id[iovec_position] to new_val
socket_last_error — Returns the last error on the socket
socket_listen — Listens for a connection on a socket
socket_read — Reads a maximum of length bytes from a socket
socket_readv — Reads from an fd, using the scatter-gather array defined by iovec_id
socket_recv — Receives data from a connected socket
socket_recvfrom — Receives data from a socket, connected or not
socket_recvmsg — Used to receive messages on a socket, whether connection-oriented or not
socket_select — Runs the select() system call on the given arrays of sockets with a timeout specified by tv_sec and tv_usec
socket_send — Sends data to a connected socket
socket_sendmsg — Sends a message to a socket, regardless of whether it is connection-oriented or not
socket_sendto — Sends a message to a socket, whether it is connected or not
socket_set_nonblock — Sets nonblocking mode for file descriptor fd
socket_set_option — Sets socket options for the socket
socket_shutdown — Shuts down a socket for receiving, sending, or both.
socket_strerror — Return a string describing a socket error
socket_write — Write to a socket
socket_writev — Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id

Stream functions

Posted by: admin  /  Category: PHP

Introduction

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other opperations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Appendix I), and additional, custom wrappers may be added either within a PHP script using stream_register_wrapper(), or directly from an extension using the API Reference. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().

Stream Filters

A filter is a final piece of code which may perform opperations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_register_filter() or in an extension using the API Reference in Chapter 43. To access the list of currently registered filters, use stream_get_filters().

A stream is referenced as: scheme://target

  • scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Appendix I for a list of PHP builtin wrappers. If no wrapper is specified, the function default is used (typically file://).
  • target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Appendix I for a description of targets for builtin streams.

Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem realted stream creation functions (i.e. fopen(), file(), file_get_contents(), etc…).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found with the list of built-in wrappers (See Appendix I).

In addition, parameters may be set on a context using stream_context_set_params(). Currently the only context parameter supported by PHP is notification. The value of this parameter must be the name of a function to be called when an event occurs on a stream. The notification function called during an event should accept the following six parameters:

void my_notifier ( int notification_code, int severity, string message, int message_code, int bytes_transferred, int bytes_max)

notification_code and severity are numerical values which correspond to the STREAM_NOTIFY_* constants listed below. If a descriptive message is available from the stream, message and message_code will be populated with the appropriate values. The meaning of these values is dependant on the specific wrapper in use. bytes_transferred and bytes_max will be populated when applicable.

Installation

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.

Stream Classes

User designed wrappers can be registered via stream_register_wrapper(), using the class definition shown on that manual page.

class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_register_filter() for details on implementing user defined filters.

Predefined Constants

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

Constant Description
STREAM_FILTER_READ Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
STREAM_FILTER_WRITE Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writting
STREAM_FILTER_ALL This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
PSFS_PASS_ON Return Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_ME Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATAL Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
STREAM_USE_PATH Flag indicating if the stream used the include path.
STREAM_REPORT_ERRORS Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT Open client socket asynchronously. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Server sockets should always include this flag.
STREAM_NOTIFY_RESOLVE A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS Indicates current progress of the stream transfer in byets_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED There is no more data available on the stream.
STREAM_NOTIFY_FAILURE A generic error occured on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO Normal, non-error realted, notification.
STREAM_NOTIFY_SEVERITY_WARN Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR A critical error occured. Processing cannot continue.

Stream Errors

As with any file or socket related function, an opperation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc…). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occours an E_WARNING message will be generated describing the nature of the error.

Examples

Example 1. Using file_get_contents() to retrieve data from multiple sources

<?php
/* Read local file from /home/bar */
$localfile = file_get_contents("/home/bar/foo.txt");

/* Identical to above, explicitly naming FILE scheme */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */
$httpfile  = file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */
$ftpfile   = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */
$ftpsfile  = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>
Example 2. Making a POST request to an https server

<?php
/* Send POST request to https://secure.example.com/form_action.php
* Include form elements named "foo" and "bar" with dummy values
*/

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&bar=" . urlencode("Value for Bar");

fputs($sock, "POST /form_action.php HTTP/1.0\r\n");
fputs($sock, "Host: secure.example.com\r\n");
fputs($sock, "Content-type: application/x-www-url-encoded\r\n");
fputs($sock, "Content-length: " . strlen($data) . "\r\n");
fputs($sock, "Accept: */*\r\n");
fputs($sock, "\r\n");
fputs($sock, "$data\r\n");
fputs($sock, "\r\n");

$headers = "";
while ($str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

print "\n";

$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>
Example 3. Writting data to a compressed file

<?php
/* Create a compressed file containing an arbitrarty string
* File can be read back using compress.zlib stream or just
* decompressed from the command line using 'gzip -d foo-bar.txt.gz'
*/
$fp = fopen("compress.zlib://foo-bar.txt.gz","wb");
if (!$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);

?>
Table of Contents
stream_context_create — Create a streams context
stream_context_get_options — Retrieve options for a stream/wrapper/context
stream_context_set_option — Sets an option for a stream/wrapper/context
stream_context_set_params — Set parameters for a stream/wrapper/context
stream_copy_to_stream — Copies data from one stream to another
stream_filter_append — Attach a filter to a stream.
stream_filter_prepend — Attach a filter to a stream.
stream_get_filters — Retrieve list of registered filters
stream_get_line — Gets line from stream resource up to a given delimiter
stream_get_meta_data — Retrieves header/meta data from streams/file pointers
stream_get_transports — Retrieve list of registered socket transports
stream_get_wrappers — Retrieve list of registered streams
stream_register_filter — Register a stream filter implemented as a PHP class derived from php_user_filter
stream_register_wrapper — Register a URL wrapper implemented as a PHP class
stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
stream_set_blocking — Set blocking/non-blocking mode on a stream
stream_set_timeout — Set timeout period on a stream
stream_set_write_buffer — Sets file buffering on the given stream
stream_socket_accept –  Accept a connection on a socket created by stream_socket_server()
stream_socket_client –  Open Internet or Unix domain socket connection
stream_socket_get_name — Retrieve the name of the local or remote sockets
stream_socket_server –  Create an Internet or Unix domain server socket

String functions

Posted by: admin  /  Category: PHP

Introduction

These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.

For information on how strings behave, especially with regard to usage of single quotes, double quotes, and escape sequences, see the Strings entry in the Types section of the manual.

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Predefined Constants

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

CRYPT_SALT_LENGTH  integer

CRYPT_STD_DES integer

CRYPT_EXT_DES integer

CRYPT_MD5 integer

CRYPT_BLOWFISH integer

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)

See Also

For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions.

Table of Contents
addcslashes — Quote string with slashes in a C style
addslashes — Quote string with slashes
bin2hex –  Convert binary data into hexadecimal representation
chop — Alias of rtrim()
chr — Return a specific character
chunk_split — Split a string into smaller chunks
convert_cyr_string –  Convert from one Cyrillic character set to another
count_chars –  Return information about characters used in a string
crc32 — Calculates the crc32 polynomial of a string
crypt — One-way string encryption (hashing)
echo — Output one or more strings
explode — Split a string by string
fprintf — Write a formatted string to a stream
get_html_translation_table –  Returns the translation table used by htmlspecialchars() and htmlentities()
hebrev –  Convert logical Hebrew text to visual text
hebrevc –  Convert logical Hebrew text to visual text with newline conversion
html_entity_decode –  Convert all HTML entities to their applicable characters
htmlentities –  Convert all applicable characters to HTML entities
htmlspecialchars –  Convert special characters to HTML entities
implode — Join array elements with a string
join — Alias for implode()
levenshtein –  Calculate Levenshtein distance between two strings
localeconv — Get numeric formatting information
ltrim –  Strip whitespace from the beginning of a string
md5_file — Calculates the md5 hash of a given filename
md5 — Calculate the md5 hash of a string
metaphone — Calculate the metaphone key of a string
money_format — Formats a number as a currency string
nl_langinfo –  Query language and locale information
nl2br –  Inserts HTML line breaks before all newlines in a string
number_format — Format a number with grouped thousands
ord — Return ASCII value of character
parse_str — Parses the string into variables
print — Output a string
printf — Output a formatted string
quoted_printable_decode –  Convert a quoted-printable string to an 8 bit string
quotemeta — Quote meta characters
rtrim –  Strip whitespace from the end of a string
setlocale — Set locale information
sha1_file — Calculate the sha1 hash of a file
sha1 — Calculate the sha1 hash of a string
similar_text –  Calculate the similarity between two strings
soundex — Calculate the soundex key of a string
sprintf — Return a formatted string
sscanf –  Parses input from a string according to a format
str_ireplace –  Case-insensitive version of str_replace().
str_pad –  Pad a string to a certain length with another string
str_repeat — Repeat a string
str_replace –  Replace all occurrences of the search string with the replacement string
str_rot13 — Perform the rot13 transform on a string
str_shuffle — Randomly shuffles a string
str_word_count –  Return information about words used in a string
strcasecmp –  Binary safe case-insensitive string comparison
strchr — Alias for strstr()
strcmp — Binary safe string comparison
strcoll — Locale based string comparison
strcspn –  Find length of initial segment not matching mask
strip_tags — Strip HTML and PHP tags from a string
stripcslashes –  Un-quote string quoted with addcslashes()
stripos –  Find position of first occurrence of a case-insensitive string
stripslashes –  Un-quote string quoted with addslashes()
stristr –  Case-insensitive strstr()
strlen — Get string length
strnatcasecmp –  Case insensitive string comparisons using a “natural order” algorithm
strnatcmp –  String comparisons using a “natural order” algorithm
strncasecmp –  Binary safe case-insensitive string comparison of the first n characters
strncmp –  Binary safe string comparison of the first n characters
strpos –  Find position of first occurrence of a string
strrchr –  Find the last occurrence of a character in a string
strrev — Reverse a string
strrpos –  Find position of last occurrence of a char in a string
strspn –  Find length of initial segment matching mask
strstr — Find first occurrence of a string
strtok — Tokenize string
strtolower — Make a string lowercase
strtoupper — Make a string uppercase
strtr — Translate certain characters
substr_count — Count the number of substring occurrences
substr_replace — Replace text within a portion of a string
substr — Return part of a string
trim –  Strip whitespace from the beginning and end of a string
ucfirst — Make a string’s first character uppercase
ucwords –  Uppercase the first character of each word in a string
vprintf — Output a formatted string
vsprintf — Return a formatted string
wordwrap –  Wraps a string to a given number of characters using a string break character.

Sybase functions

Posted by: admin  /  Category: PHP

Installation

To enable Sybase-DB support configure PHP –with-sybase[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP –with-sybase-ct[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase.

Runtime Configuration

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

Table 1. Sybase configuration options

Name Default Changeable
sybase.allow_persistent “On” PHP_INI_SYSTEM
sybase.max_persistent “-1″ PHP_INI_SYSTEM
sybase.max_links “-1″ PHP_INI_SYSTEM
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 “Off” PHP_INI_SYSTEM
magic_quotes_sybase “Off” PHP_INI_ALL

Here is a short explanation of the configuration directives.

sybase.allow_persistent  boolean

Whether to allow persistent Sybase connections.
sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.
sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.
sybase.min_error_severity integer

Minimum error severity to display.
sybase.min_message_severity integer

Minimum message severity to display.
sybase.compatability_mode boolean

Compatability mode with old versions of PHP 3.0. If on, this will cause PHP to automatically assign types to results according to their Sybase type, instead of treating them all as strings. This compatability mode will probably not stay around forever, so try applying whatever necessary changes to your code, and turn it off.
magic_quotes_sybase boolean

If magic_quotes_sybase is on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime are enabled.

Note: Note that when magic_quotes_sybase is ON it completely overrides magic_quotes_gpc . In this case even when magic_quotes_gpc is enabled neither double quotes, backslashes or NUL’s will be escaped.

Table 2. Sybase-CT configuration options

Name Default Changeable
sybct.allow_persistent “On” PHP_INI_SYSTEM
sybct.max_persistent “-1″ PHP_INI_SYSTEM
sybct.max_links “-1″ PHP_INI_SYSTEM
sybct.min_server_severity “10″ PHP_INI_ALL
sybct.min_client_severity “10″ PHP_INI_ALL
sybct.hostname NULL PHP_INI_ALL
sybct.deadlock_retry_count “-1″ PHP_INI_ALL

Here is 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.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 to define how often deadlocks are to be retried. The default is -1, or “forever”.

For further details and definition of the PHP_INI_* constants see ini_set().
Resource Types

Predefined Constants

This extension has no constants defined.

Table of Contents
sybase_affected_rows — get number of affected rows in last query
sybase_close — close Sybase connection
sybase_connect — open Sybase server connection
sybase_data_seek — move internal row pointer
sybase_deadlock_retry_count — set the deadlock retry count
sybase_fetch_array — fetch row as array
sybase_fetch_assoc — fetch row as associative array
sybase_fetch_field — get field information
sybase_fetch_object — fetch row as object
sybase_fetch_row — get row as enumerated array
sybase_field_seek — set field offset
sybase_free_result — free 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 — get number of fields in result
sybase_num_rows — Get number of rows in result
sybase_pconnect — open persistent Sybase connection
sybase_query — Send Sybase query
sybase_result — get result data
sybase_select_db — select Sybase database
sybase_set_message_handler — set handler called when a server message is raised
sybase_unbuffered_query — send Sybase query and do not block

Tokenizer functions

Posted by: admin  /  Category: PHP

Introduction

The tokenizer functions provide an interface to the PHP tokenizer embedded in the Zend Engine. Using these functions you may write your own PHP source analyzation or modification tools without having to deal with the language specification at the lexical level.

See also the appendix about tokens.
Requirements

No external libraries are needed to build this extension.
Installation

Beginning with PHP 4.3.0 these functions are enabled by default. For older versions you have to configure and compile PHP with –enable-tokenizer. You can disable tokenizer support with –disable-tokenizer.

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

Note: Builtin support for tokenizer is available with PHP 4.3.0.

Predefined Constants

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

T_INCLUDE (integer)

T_INCLUDE_ONCE (integer)

T_EVAL (integer)

T_REQUIRE (integer)

T_REQUIRE_ONCE (integer)

T_LOGICAL_OR (integer)

T_LOGICAL_XOR (integer)

T_LOGICAL_AND (integer)

T_PRINT (integer)

T_PLUS_EQUAL (integer)

T_MINUS_EQUAL (integer)

T_MUL_EQUAL (integer)

T_DIV_EQUAL (integer)

T_CONCAT_EQUAL (integer)

T_MOD_EQUAL (integer)

T_AND_EQUAL (integer)

T_OR_EQUAL (integer)

T_XOR_EQUAL (integer)

T_SL_EQUAL (integer)

T_SR_EQUAL (integer)

T_BOOLEAN_OR (integer)

T_BOOLEAN_AND (integer)

T_IS_EQUAL (integer)

T_IS_NOT_EQUAL (integer)

T_IS_IDENTICAL (integer)

T_IS_NOT_IDENTICAL (integer)

T_IS_SMALLER_OR_EQUAL (integer)

T_IS_GREATER_OR_EQUAL (integer)

T_SL (integer)

T_SR (integer)

T_INC (integer)

T_DEC (integer)

T_INT_CAST (integer)

T_DOUBLE_CAST (integer)

T_STRING_CAST (integer)

T_ARRAY_CAST (integer)

T_OBJECT_CAST (integer)

T_BOOL_CAST (integer)

T_UNSET_CAST (integer)

T_NEW (integer)

T_EXIT (integer)

T_IF (integer)

T_ELSEIF (integer)

T_ELSE (integer)

T_ENDIF (integer)

T_LNUMBER (integer)

T_DNUMBER (integer)

T_STRING (integer)

T_STRING_VARNAME (integer)

T_VARIABLE (integer)

T_NUM_STRING (integer)

T_INLINE_HTML (integer)

T_CHARACTER (integer)

T_BAD_CHARACTER (integer)

T_ENCAPSED_AND_WHITESPACE (integer)

T_CONSTANT_ENCAPSED_STRING (integer)

T_ECHO (integer)

T_DO (integer)

T_WHILE (integer)

T_ENDWHILE (integer)

T_FOR (integer)

T_ENDFOR (integer)

T_FOREACH (integer)

T_ENDFOREACH (integer)

T_DECLARE (integer)

T_ENDDECLARE (integer)

T_AS (integer)

T_SWITCH (integer)

T_ENDSWITCH (integer)

T_CASE (integer)

T_DEFAULT (integer)

T_BREAK (integer)

T_CONTINUE (integer)

T_OLD_FUNCTION (integer)

T_FUNCTION (integer)

T_CONST (integer)

T_RETURN (integer)

T_USE (integer)

T_GLOBAL (integer)

T_STATIC (integer)

T_VAR (integer)

T_UNSET (integer)

T_ISSET (integer)

T_EMPTY (integer)

T_CLASS (integer)

T_EXTENDS (integer)

T_OBJECT_OPERATOR (integer)

T_DOUBLE_ARROW (integer)

T_LIST (integer)

T_ARRAY (integer)

T_LINE (integer)

T_FILE (integer)

T_COMMENT (integer)

T_ML_COMMENT (integer)

T_OPEN_TAG (integer)

T_OPEN_TAG_WITH_ECHO (integer)

T_CLOSE_TAG (integer)

T_WHITESPACE (integer)

T_START_HEREDOC (integer)

T_END_HEREDOC (integer)

T_DOLLAR_OPEN_CURLY_BRACES (integer)

T_CURLY_OPEN (integer)

T_PAAMAYIM_NEKUDOTAYIM (integer)

T_DOUBLE_COLON (integer)

Examples

Here is a simple example PHP scripts using the tokenizer that will read in a PHP file, strip all comments from the source and print the pure code only.

Example 1. Strip comments with the tokenizer

<?php
$source = file_get_contents("somefile.php");
$tokens = token_get_all($source);
foreach ($tokens as $token) {
if (is_string($token)) {
// simple 1-character token
echo $token;
} else {
// token array
list($id, $text) = $token;
switch($id) {
case T_COMMENT:
case T_ML_COMMENT:
// no action on comments
break;
default:
// anything else -> output "as is"
echo $text;
break;
}
}
}
?>
Table of Contents
token_get_all – Split given source into PHP tokens
token_name – Get the symbolic name of a given PHP token

URL Functions

Posted by: admin  /  Category: PHP

Introduction

Dealing with URL strings: encoding, decoding and parsing.

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

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

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents
base64_decode – Decodes data encoded with MIME base64
base64_encode – Encodes data with MIME base64
get_meta_tags –  Extracts all meta tag content attributes from a file and returns an array
parse_url – Parse a URL and return its components
rawurldecode – Decode URL-encoded strings
rawurlencode – URL-encode according to RFC 1738
urldecode – Decodes URL-encoded string
urlencode – URL-encodes string
?>