BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


PHP Pocket Reference
PHP Pocket Reference

By Rasmus Lerdorf

Cover | Table of Contents


Table of Contents

Chapter 1: PHP Pocket Reference
PHP is a server-side, HTML-embedded, cross-platform scripting language—quite a mouthful. In simpler terms, PHP provides a way for you to put instructions in your HTML files to create dynamic content. These instructions are read and parsed by the web server; they never actually make it to the browser that is displaying the page. The web server replaces your PHP code with the content that the code was written to produce.
PHP can be configured to run either as a server module or as a standalone CGI script. At the time of this writing, the server-module version is only production-ready for the Apache web server on Unix systems. The CGI version runs with all web servers on both Unix and Windows 95/98/NT. On the Windows platform (as of PHP Version 4), the server module is being developed to work with ISAPI, NSAPI, and WSAPI, which means the server module will eventually work with Microsoft's IIS, Netscape's Enterprise Server, and O'Reilly's WebSite. See http://www.php.net for availability details.
The PHP language itself borrows concepts from other common languages, such as C and Perl. If you have some experience with one of these languages, you should feel right at home with PHP. In addition to the core language, PHP provides a wide variety of functions that support everything from array manipulation to regular expression support.
Database connectivity is one popular use for PHP. PHP supports a large number of databases natively and many others are accessible through PHP's ODBC functions. Through this database connectivity, it is possible, for example, to take a company's database of products and write a web interface to it using PHP.
This book provides an overview of the core PHP language and contains summaries of all the functions available in PHP. The material covers PHP 3.0.
PHP Version 3 can be installed in two primary ways: as an Apache module on Unix systems or as a CGI script on both Unix and Windows systems. See the installation instructions that come with PHP for full and current information.
When you are using PHP as an Apache module, PHP processing is triggered by a special MIME type. This is defined in the Apache configuration file with a line similar to:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
PHP is a server-side, HTML-embedded, cross-platform scripting language—quite a mouthful. In simpler terms, PHP provides a way for you to put instructions in your HTML files to create dynamic content. These instructions are read and parsed by the web server; they never actually make it to the browser that is displaying the page. The web server replaces your PHP code with the content that the code was written to produce.
PHP can be configured to run either as a server module or as a standalone CGI script. At the time of this writing, the server-module version is only production-ready for the Apache web server on Unix systems. The CGI version runs with all web servers on both Unix and Windows 95/98/NT. On the Windows platform (as of PHP Version 4), the server module is being developed to work with ISAPI, NSAPI, and WSAPI, which means the server module will eventually work with Microsoft's IIS, Netscape's Enterprise Server, and O'Reilly's WebSite. See http://www.php.net for availability details.
The PHP language itself borrows concepts from other common languages, such as C and Perl. If you have some experience with one of these languages, you should feel right at home with PHP. In addition to the core language, PHP provides a wide variety of functions that support everything from array manipulation to regular expression support.
Database connectivity is one popular use for PHP. PHP supports a large number of databases natively and many others are accessible through PHP's ODBC functions. Through this database connectivity, it is possible, for example, to take a company's database of products and write a web interface to it using PHP.
This book provides an overview of the core PHP language and contains summaries of all the functions available in PHP. The material covers PHP 3.0.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installation and Configuration
PHP Version 3 can be installed in two primary ways: as an Apache module on Unix systems or as a CGI script on both Unix and Windows systems. See the installation instructions that come with PHP for full and current information.
When you are using PHP as an Apache module, PHP processing is triggered by a special MIME type. This is defined in the Apache configuration file with a line similar to:
AddType application/x-httpd-php3 .php3
This tells Apache to treat all files that end with the .php3 extension as PHP files, which means that any file with that extension is parsed for PHP tags. The actual extension is completely arbitrary and you are free to change it to whatever you wish to use.
If you are running PHP as a dynamic shared object (DSO) module, you also need this line in your Apache configuration file:
LoadModule php3_module    modules/libphp3.so
When you are running PHP as a CGI script (with any web server), PHP processing is still triggered by this special MIME type, but a bit more work is needed. The web server needs to know that it has to redirect the request for the PHP MIME type to the CGI version of PHP. With ApacheNT, for example, this redirect is done with a set of configuration lines like the following:
ScriptAlias /php3/ "/path-to-php-dir/php.exe" 
AddType application/x-httpd-php3 .php3
Action application/x-httpd-php3 "/php3/php.exe" 
For IIS, this redirect is set up through the Windows registry. Refer to the PHP installation instructions for full details.
At runtime, most aspects of PHP can be controlled with the php3.ini file (located in /usr/local/lib by default). For the Apache module version of PHP, this file is read only when the server is started or reinitialized. Changes to this file should be treated the same as changes to Apache's own configuration files. In other words, if you make a change, you need to send your Apache server an HUB or a USR1 signal before the change will take effect.
Many aspects of PHP can also be controlled on a per-directory basis (or even per-location or per-request) when using the Apache module version. Most of the directives available in the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Embedding PHP in HTML
You embed PHP code into a standard HTML page. For example, here's how you can dynamically generate the title of an HTML document:
<HTML><HEAD><TITLE><?echo $title?></TITLE>
</HEAD>...
The <?echo $title?> portion of the document is replaced by the contents of the $title PHP variable. echo is a basic language statement that you can use to output data.
There are a few different ways that you can embed your PHP code. As you just saw, you can put PHP code between <? and ?> tags:
<? echo "Hello World"; ?>
This style is the most common way to embed PHP, but it is a problem if your PHP code needs to co-exist with XML, as XML may use that tagging style itself. If this is the case, you can turn off this style in the php3.ini file with the short_open_tag directive. Another way to embed PHP code is within <?php and ?> tags:
<?php echo "Hello World"; ?>
This style is always available and is recommended when your PHP code needs to be portable to many different systems. Embedding PHP within <SCRIPT> tags is another style that is always available:
<SCRIPT LANGUAGE="php" > echo "Hello World"; 
</SCRIPT>
One final style, where the code is between <% and %> tags, is disabled by default:
<% echo "Hello World"; %>
You can turn on this style with the asp_tags directive in your php3.ini file. The style is most useful when you are using Microsoft FrontPage or another HTML authoring tool that prefers that tag style for HTML embedded scripts.
You can embed multiple statements by separating them with semicolons:
<? 
echo "Hello World";
echo "A second statement";
?>
It is legal to switch back and forth between HTML and PHP at any time. For example, if you want to output 100 <BR> tags for some reason, you can do it this way:
<? for($i=0; $i<100; $i++) { ?>
<BR>
<? } ?>
When you embed PHP code in an HTML file, you need to use the .php3 file extension for that file, so that your web server knows to send the file to PHP for processing. Or, if you have configured your web server to use a different extension for PHP files, use that extension instead.
When you have PHP code embedded in an HTML page, you can think of that page as being a PHP program. The bits and pieces of HTML and PHP combine to provide the functionality of the program. A collection of pages that contain programs can be thought of as a web application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Language Syntax
Variable names in PHP are case-sensitive. That means that $A and $a are two distinct variables. However, function names in PHP are not case-sensitive. This applies to both built-in functions and user-defined functions.
PHP ignores whitespace between tokens. You can use spaces, tabs, and newlines to format and indent your code to make it more readable. PHP statements are terminated by semicolons.
There are three types of comments in PHP:
/* C style comments */
// C++ style comments
# Bourne shell style comments
The C++ and Bourne shell style comments can be inserted anywhere in your code. Everything from the comment characters to the end of the line is ignored. The C-style comment tells PHP to ignore everything from the start of the comment until the end-comment characters are seen. This means that this style of comment can span multiple lines.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
In PHP, all variable names begin with a dollar sign ($). The $ is followed by an alphabetic character or an underscore, and optionally followed by a sequence of alphanumeric characters and underscores. There is no limit on the length of a variable. Variable names in PHP are case-sensitive. Here are some examples:
$i
$counter
$first_name
$_TMP
In PHP, unlike in many other languages, you do not have to explicitly declare variables. PHP automatically declares a variable the first time a value is assigned to it. PHP variables are untyped; you can assign a value of any type to a variable.
Sometimes it is useful to set and use variables dynamically. Normally, you assign a variable like this:
$var = "hello";
Now let's say you want a variable whose name is the value of the $var variable. You can do that like this:
$$var = "World";
PHP parses $$var by first dereferencing the innermost variable, meaning that $var becomes "hello". The expression that is left is then $"hello", which is just $hello. In other words, we have just created a new variable named hello and assigned it the value "World". You can nest dynamic variables to an infinite level in PHP, although once you get beyond two levels, it can be very confusing for someone who is trying to read your code.
There is a special syntax for using dynamic variables inside quoted strings in PHP:
echo "Hello ${$var}";
This syntax is also used to help resolve an ambiguity that occurs when variable arrays are used. Something like $$var[1] is ambiguous because it is impossible for PHP to know which level to apply the array index to. ${$var[1]} tells PHP to dereference the inner level first and apply the array index to the result before dereferencing the outer level. ${$var}[1], on the other hand, tells PHP to apply the index to the outer level.
Dynamic variables may not initially seem that useful, but there are times when they can shorten the amount of code you need to write to perform certain tasks. For example, say you have an associative array that looks like this:
$array["abc"] = "Hello";
$array["def"] = "World";
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Types
PHP provides three primitive data types: integers, floating point numbers, and strings. In addition, there are two compound data types: arrays and objects.
Integers are whole numbers. The range of integers in PHP is equivalent to the range of the long data type in C. On 32-bit platforms, integer values can range from -2,147,483,648 to +2,147,483,647. PHP automatically converts larger values to floating point numbers if you happen to overflow the range. An integer can be expressed in decimal (base-10), hexadecimal (base-16), or octal (base-8). For example:
$decimal=16; 
$hex=0x10; 
$octal=020; 
Floating point numbers represent decimal values. The range of floating point numbers in PHP is equivalent to the range of the double type in C. On most platforms a double can range from 1.7E-308 to 1.7E+308. A double may be expressed either as a regular number with a decimal point or in scientific notation. For example:
$var=0.017; 
$var=17.0E-3
Note that PHP also has a set of functions known as the BC (binary calculator) functions. These functions can manipulate arbitrary precision numbers. If you are dealing with very large numbers or numbers that require a high degree of precision, you should use these functions.
A string is a sequence of characters. A string can be delimited by single quotes or double quotes:
'PHP is cool'
"Hello, World!"
Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not. For example:
$a="World"; 
echo "Hello\t$a\n";
This displays "Hello" followed by a tab and then "World" followed by a newline. In other words, variable substitution is performed on the variable $a and the escape sequences are converted to their corresponding characters. Contrast that with:
echo 'Hello\t$a\n';
In this case, the output is exactly "Hello\t$a\n". There is no variable substitution or handling of escape sequences.
The following table shows the escape sequences understood by PHP:
Escape Sequence
Meaning
\n
Newline
\t
Tab
\r
Carriage return
\\
Backslash
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expressions
An expression is the basic building block of the language. Anything with a value can be thought of as an expression. Examples include:
5
5+5
$a
$a==5
sqrt(9)
By combining many of these basic expressions, you can build larger and more complex expressions.
Note that the echo statement we've used in numerous examples cannot be part of a complex expression because it does not have a return value. The print statement, on the other hand, can be used as part of complex expression, as it does have a return value. In all other respects, echo and print are identical—they output data.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Operators
Expressions are combined and manipulated using operators. The following table shows the operators available in PHP, along with their precedence (P) and associativity (A). The following table lists the operators from highest to lowest precedence. These operators should be familiar to you if you have any C, Java, or Perl experience.
Operators
P
A
!, ~, ++, --, @, (the casting operators)
16
Right
*, /, %
15
Left
+, - .
14
Left
<<, >>
13
Left
<, <=, >=, >
12
Non-associative
==, !=
11
Non-associative
&
10
Left
^
9
Left
|
8
Left
&&
7
Left
||
6
Left
? : (conditional operator)
5
Left
=, +=, -=, *=, /=, %=, ^=, .=, &=, |=
4
Left
And
3
Left
Xor
2
Left
Or
1
Left
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Control Structures
The control structures in PHP are very similar to those used by the C language. Control structures are used to control the logical flow through a PHP script. PHP's control structures have two syntaxes that can be used interchangeably. The first form uses C-style curly braces to enclose statement blocks, while the second style uses a more verbose syntax that includes explicit ending statements. The first style is preferable when the control structure is completely within a PHP code block. The second style is useful when the construct spans a large section of intermixed code and HTML. The two styles are completely interchangeable, however, so it is really a matter of personal preference which one you use.
The if statement is a standard conditional found in most languages. Here are the two syntaxes for the if statement:
if(expr) {	 if(expr):
 statements	statements
}	 elseif(expr):
elseif(expr) {	statements
 statements	 else:
}	statements
else {	 endif;
 statements             
}                  
The if statement causes particular code to be executed if the expression it acts on is true. With the first form, you can omit the braces if you only need to execute a single statement.
The switch statement can be used in place of a lengthy if statement. Here are the two syntaxes for switch:
switch(expr) {         switch(expr):
 case expr:             case expr:
  statements              statements
  break;                 break;
 default:               default:
  statements              statements
  break;                 break;
}                      endswitch;
The expression for each case statement is compared against the switch expression and, if they match, the code following that particular case is executed. The break keyword signals the end of a particular case; it may be omitted, which causes control to flow into the next case. If none of the case expressions match the switch expression, the default case is executed.
The while statement is a looping construct that repeatedly executes some code while a particular expression is true:
while(
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions
A function is a named sequence of code statements that can optionally accept parameters and return a value. A function call is an expression that has a value; its value is the returned value from the function. PHP provides a large number of internal functions. The "Function Reference" section lists all of the commonly available functions. PHP also supports user-definable functions. To define a function, use the function keyword. For example:
function soundcheck($a, $b, $c) {
 return "Testing, $a, $b, $c";
}
When you define a function, you need to be careful what name you give it. In particular, you need to make sure that the name does not conflict with any of the internal PHP functions. If you do use a function name that conflicts with an internal function, you get the following error:
Fatal error: Can't redeclare already declared function in filename on line N
After you define a function, you call it by passing in the appropriate arguments. For example:
echo soundcheck(4, 5, 6);
You can also create functions with optional parameters. To do so, you set a default value for each optional parameter in the definition, using C++ style. For example, here's how to make all the parameters to the soundcheck( ) function optional:
function soundcheck($a=1, $b=2, $c=3) {
 return "Testing, $a, $b, $c";
}
The scope of a variable refers to where in a program the variable is available. If a variable is defined in the main part of a PHP script (i.e., not inside a function or a class), it is in the global scope. Note that global variables are only available during the current request. The only way to make variables in one page available to subsequent requests to another page is to pass them to that page via cookies, GET method data, or PUT method data. To access a global variable from inside a function, you need to use the global keyword. For example:
function test(  ) {
 global $var;
 echo $var;
}
$var="Hello World";
test(  );
The $GLOBALS array is an alternative mechanism for accessing variables in the global scope. This is an associative array of all the variables currently defined in the global scope:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web-Related Variables
PHP automatically creates global variables for all the data it receives in an HTTP request. This can include GET data, POST data, cookie data, and environment variables. Say you have an HTML form that looks as follows:
<FORM ACTION="test.php3" METHOD="POST">
<INPUT TYPE=text NAME=var>
</FORM>
When the form is submitted to the test.php3 file, the $var variable within that file is set to whatever the user entered in the text field.
A variable can also be set in a URL like this:
http://your.server/test.php3?var=Hello+World
When the request for this URL is processed, the $var variable is set for the test.php3 page.
Any environment variables present in your web server's configuration are also made available, along with any CGI-style variables your web server might set. The actual set of variables varies between different web servers. The best way to get a list of these variables is to use PHP's special information tag. Put the following code in a page and load the page in your browser:
<? phpinfo(  ) ?>
You should see a page with quite a bit of information about PHP and the machine it is running on. There is a table that describes each of the extensions currently enabled in PHP. Another table shows the current values of all the various configuration directives from your php3.ini file. Following those two tables are more tables showing the regular environment variables, the special PHP internal variables, and the special environment variables that your web server has added. Finally, the HTTP request and response headers for the current request are shown.
Sometimes it is convenient to create a generic form handler, where you don't necessarily know all the form element names. To support this, PHP provides GET, POST, and cookie associative arrays that contain all of the data passed to the page using the different techniques. These arrays are named $HTTP_GET_DATA, $HTTP_POST_DATA, $HTTP_COOKIE_DATA, respectively. For example, here's another way to access the value of the text field in our form:
echo $HTTP_POST_VARS["var"];
PHP sets global variables in a particular order. By default, global variables are set first from GET data, then from POST data, and then finally from cookie data. This means that if you have a form with a field named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Examples
The best way to understand the power of PHP is to examine some real examples of PHP in action, so we'll look at some common uses of PHP in this section.
Here is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your browser:
<HTML><HEAD><TITLE>PHP Example</TITLE></HEAD>
<BODY>
You are using <? echo $HTTP_USER_AGENT ?><BR>
and coming from <? echo $REMOTE_ADDR ?>
</BODY></HTML>
You should see something like the following in your browser window:
You are using Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) 
and coming from 207.164.141.23
Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name and select one or more interests from a selection box. We could do this in two files, where we separate the actual form from the data handling code, but instead, this example shows how it can be done in a single file:
<HTML><HEAD><TITLE>Form Example</TITLE></HEAD>
<BODY>
<H1>Form Example</H1>
<?
function show_form($first="", $last="",
                   $interest=""){
 $options = array("Sports", "Business",
                  "Travel", "Shopping",
                  "Computers");
 if(empty($interest)) $interest=array(-1);
?>
<FORM ACTION="form.php3" METHOD="POST">
First Name: 
<INPUT TYPE=text NAME=first 
       VALUE="<?echo $first?>">
<BR>
Last Name: 
<INPUT TYPE=text NAME=last 
       VALUE="<?echo $last?>">
<BR>
Interests: 
<SELECT MULTIPLE NAME=interest[]>
<? 
 for($i=0, reset($interest); 
     $i<count($options); $i++){
  echo "<OPTION";
  if(current($interest)==$options[$i]) {
   echo " SELECTED ";
   next($interest);
  }
  echo "> $options[$i]\n";
 }
?>
</SELECT><BR>
<INPUT TYPE=submit>
</FORM>
<? }

if(!isset($first)) {
 show_form();
} 
else {
 if(empty($first) || empty($last) || 
  count($interest) == 0) {
  echo "You did not fill in all the ";
  echo "fields, please try again<P>\n";
  show_form($first,$last,$interests);
 } 
 else { 
  echo "Thank you, $first $last, you ";
  echo "selected ". join(" and ", $interest);
  echo " as your interests.<P>\n";
 }
}
?>
</BODY></HTML>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Function Reference
The remaining sections summarize the internal functions that are available in PHP. The synopsis for each function lists the expected argument types for the function and its return type. The possible types are int, double, string, array, void, and mixed. mixed means that the argument or return type can be of any type. Optional arguments are shown in square brackets.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Array Functions
PHP supports arrays that are indexed both by integers and by arbitrary strings—known as associative arrays. Internally, PHP does not distinguish between associative arrays and integer-indexed arrays, as arrays are implemented as hash tables. Here are the array functions supported by PHP:
array array(...)
Create an array that contains all of the specified arguments
int array_walk(array array_arg, string function)
Apply a function to every member of an array
int arsort(array array_arg)
Sort an array in reverse order and maintain index association
int asort(array array_arg)
Sort an array and maintain index association
int count(mixed var)
Count the number of elements in a variable (usually an array)
mixed current(array array_arg)
Return the element currently pointed to by the internal array pointer
array each(array array_arg)
Return the next key/value pair from an array
mixed end(array array_arg)
Advance the array's internal pointer to the last element and return the value of that element
void extract(array var_array, int extract_type [, string prefix])
Import variables into a symbol table from an array
mixed key(array array_arg)
Return the key of the element currently pointed to by the internal array pointer
int krsort(array array_arg)
Sort an array in reverse by key
int ksort(array array_arg)
Sort an array by key
mixed max(mixed arg1 [, mixed arg2 [, ...]])
Return the highest value in an array or a series of arguments
mixed min(mixed arg1 [, mixed arg2 [, ...]])
Return the lowest value in an array or a series of arguments
mixed next(array array_arg)
Move the array's internal pointer to the next element and return the value of that element
mixed pos(array array_arg)
An alias for current( )
mixed prev(array array_arg)
Move the array's internal pointer to the previous element and return the value of that element
array range(int low, int high)
Create an array containing the range of integers from low to high (inclusive)
mixed reset(array array_arg)
Set the array's internal pointer to the first element and return the value of that element
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Configuration and Logging Functions
Here are functions for getting and setting PHP configuration options at runtime, as well as logging and other functions that are useful during debugging:
int debugger_off(void)
Disable the internal PHP debugger
int debugger_on(string ip_address)
Enable the internal PHP debugger
int error_log(string message, int message_type [, string destination] [, string extra_headers])
Send an error message somewhere
int error_reporting([int level])
Set/get the current error reporting level
string get_cfg_var(string option_name)
Get the value of a PHP configuration option
int get_magic_quotes_gpc(void)
Get the current active configuration setting of magic_quotes_gpc
int get_magic_quotes_runtime(void)
Get the current active configuration setting of magic_quotes_runtime
void phpinfo(void)
Output a page of useful information about PHP and the current request
string phpversion(void)
Return the current PHP version
int set_magic_quotes_runtime(int new_setting)
Set the current active configuration setting of magic_quotes_runtime and return the previous value
void set_time_limit(int seconds)
Set the execution time limit for the current script
int short_tags(int state)
Turn the short tags option on or off and return the previous state
The syslog functions provide an interface to the Unix syslog facility. On NT, these functions have been abstracted to use NT's Event Log mechanism instead:
int closelog(void)
Close the connection to the system logger
void define_syslog_variables(void)
Initialize all syslog-related variables
int openlog(string ident, int option, int facility)
Open a connection to the system logger
int syslog(int priority, string message)
Generate a system log message
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Database Functions
PHP supports a number of databases directly through the databases' own native APIs. Each of the databases is covered in a separate section. Many of the databases can also be accessed through ODBC if appropriate ODBC drivers are available for that particular database. Adabas-D, Solid, Empress, Velocis and IBM DB2 have native APIs that are so similar to the ODBC API that having a separate set of functions for each one was redundant. So, for these five databases, use the ODBC set of functions. It is important to understand, however, that for those five databases, the actual communication is direct and native and does not go through any sort of intermediary ODBC layer.
PHP allows 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 deleted records are kept until you call dbase_pack( ). Unlike with SQL databases, once a dBase file is created, the database definition is fixed. There are no indexes that speed searching or otherwise organize your data. Because of these limitations, I don't recommend using dBase files as your production database. Choose a real SQL server, such as MySQL or Postgres, instead. PHP provides dBase support to allow you to import and export data to and from your web database, as the format is understood by Windows spreadsheets and organizers. In other words, the import and export of data is about all that the dBase support is good for.
Here are the dBase functions supported by PHP:
bool dbase_add_record(int identifier, array data)
Add a record to the database
bool dbase_close(int identifier)
Close an open dBase-format database file
bool dbase_create(string filename, array fields)
Create a new dBase-format database file
bool dbase_delete_record(int identifier, int record)
Mark a record to be deleted
array dbase_get_record(int identifier, int record)
Return an array representing a record from the database
array dbase_get_record_with_names(int identifier, int record)
Return an associative array representing a record from the database
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Date/Time Functions
PHP provides the following functions for working with dates and times:
bool checkdate(int month, int day, int year)
Validate a date/time
string date(string format[, int timestamp])
Format a local date/time
array getdate([int timestamp])
Get date/time information
array gettimeofday(void)
Return the current time as an array
string gmdate(string format[, int timestamp])
Format a GMT/CUT date/time
int gmmktime(int hour, int min, int sec, int mon, int mday, int year)
Get Unix timestamp for a GMT date
string gmstrftime(string format[, int timestamp])
Format a GMT/CUT time/date according to local settings
string microtime(void)
Return a string containing the current time in seconds and microseconds
int mktime(int hour, int min, int sec, int mon, int mday, int year)
Get Unix timestamp for a date
string strftime(string format[, int timestamp])
Format a local time/date according to local settings
int time(void)
Return current Unix timestamp
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Directory Functions
The following functions are used to manipulate directories. For example, to open the current directory and read in all the entries, you can do something like this:
$handle = opendir('.'); 
while($entry = readdir($handle)) { 
   echo "$entry<br>\n";
} 
closedir($handle); 
PHP supports a dir class that represents a directory. Here's an example of using this object-oriented approach to reading a directory:
$d = dir("/etc");
echo "Handle: ".$d->handle."<br>\n";
echo "Path: ".$d->path."<br>\n";
while($entry=$d->read(  )) {
   echo $entry."<br>\n";
}
$d->close(  );
In addition to the read( ) and close( ) methods, the dir class supports a rewind( ) method.
Here are the directory functions supported by PHP:
int chdir(string directory)
Change the current directory
void closedir([int dir_handle])
Close the directory connection identified by the dir_handle, or a previously opened directory if not specified
class dir(string directory)
Return a class with handle and path properties as well as read, rewind, and close methods
int opendir(string directory)
Open a directory and return a dir_handle
string readdir(int dir_handle)
Read a directory entry from dir_handle
void rewinddir(int dir_handle)
Rewind dir_handle back to the start
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
File Functions
The following functions manipulate the local filesystem or data from the filesystem in some manner:
string basename(string path)
Return the filename component of the path
int chgrp(string filename, mixed group)
Change the file group
int chmod(string filename, int mode)
Change the file mode
int chown(string filename, mixed user)
Change the file owner
void clearstatcache(void)
Clear the file stat cache
int copy(string source_file, string destination_file)
Copy a file
string dirname(string path)
Return the directory name component of the path
bool diskfree(string path)
Return the number of free kilobytes in path
int fclose(int fp)
Close an open file pointer
int feof(int fp)
Test for end-of-file on a file pointer
string fgetc(int fp)
Get a character from the file pointer
array fgetcsv(int fp, int length)
Get line from file pointer and parse for CSV fields
string fgets(int fp, int length)
Get a line from the file pointer
string fgetss(int fp, int length [, string allowable_tags])
Get a line from the file pointer and strip HTML tags
array file(string filename [, int use_include_path])
Read an entire file into an array
int file_exists(string filename)
Check whether a file exists or not
int fileatime(string filename)
Get the last access time for a file
int filectime(string filename)
Get the last inode status change for a file
int filegroup(string filename)
Return the group ID of the file
int fileinode(string filename)
Return the inode number of the file
int filemtime(string filename)
Return the time the file was last modified
int fileowner(string filename)
Return the user ID of the owner of the file
int fileperms(string filename)
Return the file permission bits of the file
int filesize(string filename)
Return the size of the file
string filetype(string filename)
Return the type of the file (fifo, char, block, link, file, or unknown)
bool flock(int fp, int operation)
Place or remove an advisory lock on a file
int fopen(string filename, string mode [, int use_include_path])
Open a file or a URL and return a file pointer
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Graphics Functions
The graphics functions in PHP can be used to dynamically create a GIF image stream. This stream can either be sent directly to the browser or saved in a standard GIF file. The following example illustrates a number of these image functions:
Header("Content-type: image/gif");
if(!isset($s)) $s=11;
$size = imagettfbbox($s,0, 
  "/fonts/TIMES.TTF",$text);
$dx = abs($size[2]-$size[0]);
$dy = abs($size[5]-$size[3]);
$xpad=9; $ypad=9;
$im = imagecreate($dx+$xpad,$dy+$ypad);
$blue = ImageColorAllocate($im,0x2c,0x6D,
  0xAF);
$black = ImageColorAllocate($im,0,0,0);
$white = ImageColorAllocate($im,255,255,255);
ImageRectangle($im,0,0,$dx+$xpad-1,
  $dy+$ypad-1, $black);
ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,
  $white); 
ImageTTFText($im, $s, 0, (int)($xpad/2)+1, 
  $dy+(int)($ypad/2), $black, 
  "/fonts/TIMES.TTF", $text);
ImageTTFText($im, $s, 0, (int)($xpad/2), 
  $dy+(int)($ypad/2)-1, $white, 
  "/fonts/TIMES.TTF", $text);
ImageGif($im);
ImageDestroy($im);
This example should be saved as a file named button.php3, for example, and then called as part of an HTML <IMG> tag like this:
<IMG SRC="button.php3?s=13&text=Help" >. 
This produces a blue-shaded button with white shadowed text using a 13-point Times font.
Because of Unisys patent issues, the GD library (as of version 1.6) that PHP links against to generate GIF images no longer supports the GIF format. Older versions of the GD library will continue to work fine with PHP, and as of PHP-3.0.13 you can use the later versions of GD to create images in the PNG format. In the above example, you simply change the ImageGif($im) call to ImagePng($im).
Here are the graphics functions provided by PHP:
array getimagesize(string filename [, array info])
Get the size of a GIF, JPG, or PNG image as a four-element array
int imagearc(int im, int cx, int cy, int w, int h, int s, int e, int col)
Draw a partial ellipse
int imagechar(int im, int font, int x, int y, string c, int col)
Draw a character
int imagecharup(int im, int font, int x, int y, string c, int col)
Draw a character rotated 90 degrees counter-clockwise
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HTTP Functions
These functions assist you in dealing with the HTTP protocol. The encoding and decoding functions are not normally needed, as PHP takes care of these actions automatically. But there are cases where the actions need to be done manually, so these functions are provided. The header and cookie functions are useful for either sending custom HTTP headers or sending cookies.
Here are the HTTP functions in PHP:
int header(string str)
Send a raw HTTP header
int headers_sent(void)
Return true if headers have already been sent, false otherwise
array parse_url(string url)
Parse a URL and return its components in an array
string rawurldecode(string str)
Decode a URL-encoded string
string rawurlencode(string str)
URL-encode a string
void setcookie(string name [, string value [, int expire [, string path [, string domain [, int secure ]]]]])
Send a cookie
string urldecode(string str)
Decode a URL-encoded string
string urlencode(string str)
URL-encode a string
The following HTTP functions are only available if PHP is running as an Apache module:
class apache_lookup_uri(string URI)
Perform a partial request of the given URI to obtain information about it
string apache_note(string note_name [, string note_value])
Get and set Apache request notes
array getallheaders(void)
Fetch all HTTP request headers
int virtual(string filename)
Perform an Apache subrequest
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
IMAP Functions
These functions are used to communicate with mail and news servers via the IMAP4, POP3, or NNTP protocols. For these functions to work, you have to compile PHP with - - with-imap. That requires the C-client library to be installed. You can get the latest version from ftp://ftp.cac.washington.edu/imap/.
Here are the IMAP functions:
string imap_8bit(string text)
Convert an 8-bit string to a quoted-printable string
string imap_alerts(void)
Return an array of all IMAP alerts
int imap_append(int stream_id, string folder, string message [, string flags])
Append a string message to a specified mailbox
string imap_base64(string text)
Decode base64-encoded text
string imap_binary(string text)
Convert an 8-bit string to a base64-encoded string
string imap_body(int stream_id, int msg_no [, int options])
Read the message body
object imap_bodystruct(int stream_id, int msg_no, int section)
Read the structure of a specified body section of a specific message
object imap_check(int stream_id)
Get mailbox properties
void imap_clearflag_full(int stream_id, string sequence, string flag [, int options])
Clear flags on messages
int imap_close(int stream_id [, int options])
Close an IMAP stream
int imap_create(int stream_id, string mailbox)
An alias for imap_createmailbox( )
int imap_createmailbox(int stream_id, string mailbox)
Create a new mailbox
int imap_delete(int stream_id, int msg_no)
Mark a message for deletion
bool imap_deletemailbox(int stream_id, string mailbox)
Delete a mailbox
string imap_errors(void)
Return an array of all IMAP errors
int imap_expunge(int stream_id)
Delete all messages marked for deletion
array imap_fetch_overview(int stream_id, int msg_no)
Read an overview of the information in the headers of the given message
string imap_fetchbody(int stream_id, int msg_no, int section [, int options])
Get a specific body section
string imap_fetchheader(int stream_id, int msg_no [, int options])
Get the full, unfiltered header for a message
object imap_fetchstructure(int stream_id, int msg_no [, int options])
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
LDAP Functions
The following functions are used to communicate with a Lightweight Directory Access Protocol (LDAP) server. See http://www.openldap.org for a PHP-compatible free LDAP implementation.
int ldap_add(int link, string dn, array entry)
Add entries to an LDAP directory
int ldap_bind(int link [, string dn, string password])
Bind to an LDAP directory
int ldap_close(int link)
Alias for ldap_unbind( )
int ldap_connect([string host [, int port]])
Connect to an LDAP server
int ldap_count_entries(int link, int result)
Count the number of entries in a search result
int ldap_delete(int link, string dn)
Delete an entry from a directory
string ldap_dn2ufn(string dn)
Convert a distinguished name to a user friendly naming format
string ldap_err2str(int errno)
Convert error number to error string
int ldap_errno(int link)
Get the current LDAP error number
string ldap_error(int link)
Get the current LDAP error string
array ldap_explode_dn(string dn, int with_attrib)
Split a distinguished name into its component parts
string ldap_first_attribute(int link, int result, int ber)
Return the first attribute
int ldap_first_entry(int link, int result)
Return the first result ID
int ldap_free_result(int result)
Free result memory
array ldap_get_attributes(int link, int result)
Get attributes from a search result entry
string ldap_get_dn(int link, int result)
Get the distinguished name of a result entry
array ldap_get_entries(int link, int result)
Get all result entries
array ldap_get_values(int link, int result, string attribute)
Get all values from a result entry
array ldap_get_values_len(int link, int result, string attribute)
Get all values from a result entry
int ldap_list(int link, string base_dn, string filter [, string attributes])
Single-level search
int ldap_mod_add(int link, string dn, array entry)
Add attribute values to current entry
int ldap_mod_del(int link, string dn, array entry)
Delete attribute values
int ldap_mod_replace(int link, string dn, array entry)
Replace attribute values with new ones
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Math Functions
There are two types of math functions in PHP. The first type is the standard functions that operate on regular numbers. The scope and precision of these functions is limited by the operating system:
int abs(int number)
Return the absolute value of the number
double acos(double number)
Return the arc cosine of the number in radians
double asin(double number)
Return the arc sine of the number in radians
double atan(double number)
Return the arc tangent of the number in radians
double atan2(double y, double x)
Return the arc tangent of y/x, with the resulting quadrant determined by the signs of y and x
string base_convert(string number, int frombase, int tobase)
Convert a number in a string from any base to any other base (where both bases are less than or equal to 36)
int bindec(string binary_number)
Return the decimal equivalent of the binary number
int ceil(double number)
Return the next higher integer value of the number
double cos(double number)
Return the cosine of the number in radians
string decbin(int decimal_number)
Return a string containing a binary representation of the number
string dechex(int decimal_number)
Return a string containing a hexadecimal representation of the given number
string decoct(int octal_number)
Return a string containing an octal representation of the given number
double deg2rad(double degrees)
Convert the number in degrees to the radian equivalent
double exp(double number)
Return e raised to the power of the number
int floor(double number)
Return the next lower integer value from the number
int hexdec(string hexadecimal_number)
Return the decimal equivalent of the hexadecimal number