Sai Gopal Wordpress Blog

saigopal wordpress blog

Saigopal's website

Saigopal's website

My Daughter Website

Weebly

Palwow

Freelance Jobs

Thursday, May 27, 2010

Appendix - B-I AND INDEX AND TEAM DDI

C
PHP5 Functions
This appendix lists some of the functions that will be applicable if you are using the Apache/
PHP/MySQL components. PHP has numerous other functions available to you, and you can find
a complete listing in the manual at the source Web site, www.php.net. We have not included any
function that may be in the experimental stage or that isn’t fully documented on the PHP site at
the time of writing.
Note that some of the functions listed here have optional parameters that can be used to further
specify the function (noted in brackets in our listing). In the interest of simplicity, some of those
optional parameters have not been explained here, so you are encouraged to visit the source Web
site for more information.
Functions that were added in PHP5 are indicated in bold print.
Note to Windows users: Some PHP functions are designed to work on non-Windows platforms
only. If you encounter otherwise unexplained errors in your code, you might try checking the
source Web site to ensure that your function is Windows-compatible.
Apache/PHP Functions
PHP uses these functions with the Apache server.
PHP Function Description
apache_child_terminate() Stops the Apache server from running after the
PHP script has been executed.
apache_get_modules() Returns an array of loaded Apache Modules.
apache_get_version() Returns the version of Apache that is currently
running.
apache_getenv() Returns an Apache subprocess_env variable.
Table continued on following page
PHP Function Description
apache_lookup_uri(filename) Returns information about the URI in filename as a
class.
apache_note(note_name [, Returns or sets values in the Apache notes tables as
note_value]) strings.
apache_request_headers() Returns all HTTP headers as arrays.
apache_response_headers() Returns all Apache response headers as arrays.
apache_setenv(variable, Sets an Apache subprocess environment variable.
value[, bool])
ascii2ebcdic(string) Converts ASCII code to EBCDIC, opposite of
ebcdic2ascii().
ebcdic2ascii(string) Converts EBCDIC to ASCII code, opposite of
ascii2ebcdic().
getallheaders() Returns all HTTP request headers as arrays.
virtual(filename) Performs an Apache subrequest, returns an integer.
Array Functions
You can perform these functions on arrays of information.
Function Description
array([...]) Depending on the parameters, this creates an array
of values.
array_change_key_case(array[, Converts the keys in the named array to either all
case]) uppercase or all lowercase.
array_chunk(array, size[, Splits the array into chunks based on the named
keep_keys]) parameters.
array_combine(keys, values) Combines two arrays with equal number of keys and
values. Uses one array for keys and the other for
values.
array_count_values(array) Counts the number of times each value appears, and
returns results in array format.
array_diff_assoc(arrays) Finds the values from the first array that do not
appear in subsequent arrays, but unlike
array_diff(), this takes key values into account.
array_diff(arrays) Opposite of array_intersect(), finds the values
from the first array that do not appear in subsequent
arrays, and returns results in array format.
708
Appendix C
Function Description
array_diff_uassoc(arrays) Similar to array_diff_assoc(), but allows a final
check through a custom function.
array_fill(array, number, Fills an array with named value, a named number of
value) times.
array_filter(array[, criteria]) Returns only array values that fit the named criteria.
array_flip(array) Flips the array values and keys and returns results in
array format.
array_intersect_assoc(arrays) Finds the values from the first array that do not
appear in subsequent arrays, but unlike
array_intersect(), this takes key values into
account.
array_intersect(arrays) Opposite of array_diff(), finds the values from
the first array that appear in subsequent arrays, and
returns results in array format.
array_intersect_uassoc(arrays) Similar to array_intersect_assoc(), but allows
a final index check.
array_key_exists(array, search) Verifies whether or not a key exists for an array.
array_keys(array[,search_value]) Will find either all the keys in the named array, or
those keys containing the search value specified, and
returns results in an array format.
array_map(criteria, array) Applies a criterion to every element of the array and
returns the new array of elements that fit the applied
criterion.
array_merge(arrays) Merges named arrays together and returns results in
an array format. If two arrays have the same string
keys, the later array will overwrite an earlier key,
and if two arrays have the same numeric keys, the
array will be appended instead of overwritten.
array_merge_recursive(arrays) Similar to array_merge(), but the values of the
arrays are appended.
array_multisort(array[, mixed]) Sorts either a complex multidimensional array or
several arrays at one time.
array_pad(array, pad_size, Copies the existing array and pads the named size
pad_value) and value, returns value in array format.
array_pop(array) Similar to array_shift(), except this deletes the
last value of an array and returns what was deleted.
Table continued on following page
709
PHP5 Functions
Function Description
array_push(array, variables) Similar to array_unshift(), except this adds the
named values to the end of the array and returns the
updated number of values in the array.
array_rand(array [,number]) Chooses a random value from the named array and
if number is specified, chooses number of random
values from the named array. The random value that
was chosen is returned (or if more than one value is
chosen, results are returned in array format).
array_reduce(array, function) Reduces the array to a single function based on the
named parameters.
array_reverse(array) Reverses the order of the values in the array, and
results are returned in array format.
array_search(exp, array) Searches the array for the named expression and
returns the key if it exists.
array_shift(array) Similar to array_pop(), except this deletes the first
value of an array and returns what was deleted.
Opposite of array_unshift().
array_slice(array, offset[, Based on the named offset, this will create a
length]) subarray from the original array. New array that is
returned will also be length (if named).
array_splice(array, offset[, Based on the named offset, this will remove a section
length, new_values]) of the named array (and replace it with new values if
they are named).
array_sum(array) Calculates the sum of the values in the named array.
array_udiff_assoc(arrays) Returns an array with all the values that are not
present in any of the other arrays; allows an index
check and user-defined callback function.
array_udiff(arrays) Returns the difference in arrays using a user-defined
callback function.
array_udiff_uassoc(arrays) Returns the difference in arrays; allows an index
check and compares data and indexes with a userdefined
callback function.
array_uintersect_assoc(arrays) Returns the intersection of arrays through a userdefined
callback function; allows an index check.
array_uintersect(arrays) Returns the intersection of arrays through a userdefined
callback function.
array_uintersect_uassoc(arrays) Returns the intersection of arrays; allows an index
check and compares data and indexes with a userdefined
callback function.
710
Appendix C
Function Description
array_unique(array) Deletes any duplicate values in array, and returns
new array.
array_unshift(array, variables) Similar to array_push(), except this adds the
named values to the beginning of an array and
returns the number of updated values in the array.
Opposite of array_shift().
array_values(array) Returns an array with the values in the named array.
array_walk(array, Applies the named function (based on named
function[,parameter]) parameters) to every value in the array.
array_walk_recursive(array, Applies the named function recursively (based on
function[ ,parameter]) named parameters) to every value in the array.
arsort(array) Sorts the array in descending order (while maintaining
the key/value relationship).
asort(array) Sorts the array in ascending order (while maintaining
the key/value relationship).
compact(variables) Merges the variables named into one array, returns
results in array format.
count(array) Equal to sizeof(), this counts the number of values
in the named array and returns the results in an
integer format.
current(array) Returns the current values in the named array.
each(array) Creates an array with the key and value of the
current element of the named array, and returns
results in array format.
end(array) Sets the last value as the current value.
extract(array[, type, prefix]) Takes the named array and imports values into the
symbol table. The type option directs the server
what to do if there is a conflict, and prefix adds a
prefix to variable names.
in_array(value, array) Lets you know whether or not a specified value
exists in the array.
key(array) Returns the key for the current value in the array.
krsort(array) Sorts the keys in the array in reverse order and
maintains the key/value relationship.
ksort(array) Sorts the keys in the array and maintains the key/
value relationship.
list(variables) Lists the named variables.
Table continued on following page
711
PHP5 Functions
Function Description
natsort(array) Uses “natural ordering” to sort alphanumeric strings
(case-sensitive).
natcasesort(array) Uses “natural ordering” to sort alphanumeric strings
(case-insensitive).
next(array) The opposite of prev(), returns the value of the
“next” element from the current element and returns
false if the current element is the last element in
the array.
pos(array) Returns the value of the current element. (This
function is the same as current(array).
prev(array) The opposite of next(), returns the value of the
element “before” the current element, and returns
false if the current element is the first element in
the array.
range(low, high) Creates a new array of integers between the named
parameters, and returns results in an array format.
reset(array) Sets the current element as the first element in the
array, and returns its value.
rsort(array) The opposite of sort(), this sorts the array in
descending order.
shuffle(array) Shuffles the array in random order.
sizeof(array) Equal to count(), returns the number of values in
the array.
sort(array) The opposite of rsort(), this sorts the array in
ascending order.
uasort(array, function) Using the named function, this sorts the array
accordingly and maintains the key/value
relationship.
uksort(array, function) Using the named function, this sorts the array by
key.
usort(array, function) Using the named function, this sorts the array by
value.
Date/Time/Calendar Functions
The following are helpful functions built into PHP that you can use to work with dates, times, and calendar
settings. Please note that if you have installed PHP on a Linux system, you will need to compile PHP
with --enable-calendar.
712
Appendix C
Function Description
cal_days_in_month(calendar, Returns the number of days in the named month.
month, year)
cal_from_jd(julian_day, Converts a Julian Day Count into a date of a specified
calendar) calendar.
cal_info([calendar]) Returns information about the named calendar.
cal_to_jd(calendar, month, Converts a specified calendar date into a Julian Day
day, year) Count.
checkdate(month, day, year) Validates the named date and returns true or false.
date(format [, timestamp]) Returns the date (and time if named) of the local server
based on the named format. See the next table for
common formatting guidelines.
easter_date([year]) Gives the UNIX timestamp for midnight on Easter of
the current year, or the named year if present.
easter_days([year]) Calculates the number of days between March 21 and
Easter of the current year, or named year if present.
frenchtojd(french) Converts from French Republican calendar to Julian
Day Count.
getdate(timestamp) Creates an array with the named date/timestamps.
gettimeofday() Creates an array with the current time.
gmdate(format[,timestamp]) Formats a GMT date and time based on named
parameters. See the next table for common formatting
guidelines.
gmmktime([hour, minute, Gives the UNIX timestamp for GMT time/day based
second, month, day, year, on the named parameters, or the current time/day if
is_dst]) not named.
gmstrftime(format, timestamp) Formats a GMT/CUT date/time based on geography.
See the next table for common formatting guidelines.
gregoriantojd(gregorian) Converts from Gregorian calendar to Julian Day Count.
idate(string[, int]) Formats a date/time as an integer.
jddayofweek(julianday, mode) Gives day of week of Julian Day Count, based on
format named in mode.
jdmonthname(julianday, mode) Gives month of Julian Day Count, based on format
named in mode.
jdtofrench(julianday) Converts from Julian Day Count to French Republican
calendar.
jdtogregorian(julianday) Converts from Julian Day Count to Gregorian calendar.
Table continued on following page
713
PHP5 Functions
Function Description
jdtojewish(julianday) Converts from Julian Day Count to Jewish calendar.
jdtojulian(julianday) Converts from Julian Day Count to Julian Calendar
Date.
jdtounix(julianday) Converts from Julian Day Count to UNIX timestamp.
jewishtojd(jewish) Converts from Jewish calendar to Julian Day Count.
juliantojd(julian) Converts from Julian calendar to Julian Day Count.
localtime([timestamp, Finds and returns local time in array format.
is_associative])
microtime() Calculates and returns seconds and microseconds since
00:00:00 January 1, 1970.
mktime([hour, minute, second, Gives the UNIX timestamp for time/day based on
month, day, year]) named parameters, or current time/day if not named.
strftime(format [,timestamp]) Based on format and current location, this will format
the local time and date. See the next table for common
formatting guidelines.
strtotime(time[, now]) Converts a time/date format in common English into a
UNIX timestamp.
time() Gives current UNIX timestamp.
unixtojd(timestamp) Converts from UNIX timestamp to Julian Day Count.
Dates can be formatted with the following formatting codes (in conjunction with date()):
Format Character Description What Is Returned
a Lowercase ante meridian and post meridian. am, pm
A Uppercase ante meridian and post meridian. AM, PM
B Swatch Internet time. 000 through 999
c ISO8601 date. 2000-01-12T15:19:21+00:00
d Day of the month in 2 digits with leading 01 to 31
zeros.
D Day of the week in text, abbreviated to Mon through Sun
three letters.
F Month name in text format, unabbreviated. January through
December
g Hour in 12-hour format, without leading 1 through 12
zeros.
714
Appendix C
715
PHP5 Functions
Format Character Description What Is Returned
G Hour in 24-hour format, without leading 0 through 23
zeros.
h Hour in 12-hour format, with leading zeros. 01 through 12
H Hour in 24-hour format, with leading zeros. 00 through 23
i Minutes with leading zeros. 00 to 59
I (capital “i”) Indicates if date is in daylight savings time. 1 if DST, 0 otherwise
j Day of the month without leading zeros. 1 to 31
l (lowercase ‘L’) Day of the week in text, unabbreviated. Sunday through Saturday
L Indicates if the current year is a leap year. 1 if it is a leap year, 0
otherwise
m Month in numeric format, with leading 01 through 12
zeros.
M Month in text format, abbreviated to three Jan through Dec
letters.
n Month in numeric format without leading 1 through 12
zeros.
O Difference to Greenwich time (GMT) in -0500
hours.
r RFC 822 formatted date. Mon, 25 Aug 2003 18:01:01
+0200
s Seconds, with leading zeros. 00 through 59
S English ordinal suffix for the day of the st, nd, rd, or th
month, 2 characters.
t Number of days in the month. 28 through 31
T Time zone setting of the server. EST, MDT, and so on
U Seconds since the Unix Epoch (January 1
1970 00:00:00 GMT).
w Day of the week in numeric format. 0 (for Sunday) through 6
(for Saturday)
W ISO-8601 week number of year, weeks 1–52
starting on Monday.
Y Year in numeric format in 4 digits. 2000, 2001, and so on
y Year in numeric format in 2 digits. 00, 01, 02, and so on
z Day of the year in numeric format. 0 through 366
Table continued on following page
716
Appendix C
Format Character Description What Is Returned
Z Time zone offset in seconds. The offset for -43200 through 43200
time zones west of UTC is always negative,
and for those east of UTC is always
positive.
Class/Object/Function Handling Functions
The functions in the table that follows are used when referencing and working with classes, objects, and
custom functions in your PHP code.
Function Description
call_user_func(function_name[, Calls the named user-defined function.
parameters])
call_user_func_array(function_name[, Calls the named user-defined function based
parameters]) on the array of parameters.
class_exists(class_name) Verifies whether or not the class has been
defined.
create_function (arguments, code) Creates a function based on the parameters
and returns a unique name for the function.
func_get_arg(argument_num) Returns an item from the argument list.
func_get_args() Gets complete argument list.
func_num_args() Returns the number of arguments in the
argument list.
function_exists(function_name) Verifies whether or not a function has been
defined.
get_class(object_name) Returns the name of the specified object’s class.
get_class_methods(class_name) Returns the methods for specified class, in an
array format.
get_class_vars(class_name) Returns the properties for the specified class,
in an array format.
get_declared_classes() Returns all the classes that have been defined,
in an array format.
get_declared_interfaces() Returns the names of the declared interfaces.
get_defined_functions() Returns all the functions that have been
defined, in an array format.
get_object_vars(object_name) Returns the properties for the specified object,
in an array format.
Function Description
get_parent_class(object_name) Returns the name of the specified object’s
parent class.
is_a(object_name, class_name) Verifies whether an object is part of the named
class or if the class is one of the object’s
parents.
is_subclass_of(object_name, Verifies whether and object is a part of a
superclass) subclass of the named superclass.
method_exists(object_name, Verifies whether a method has been defined.
method_name)
register_shutdown_function(function) Sets up the named function to be executed
when script has been processed.
register_tick_function(function) Registers a function for execution upon every
tick.
unregister_tick_function(function) Unregisters a function previously registered
using register_tick_function().
Directory and File Functions
These functions can modify your directory settings and allow you to work with files through your PHP
script.
Function Description
basename(path) Returns the filename listed in the named path.
chdir(directory) Makes the named directory the current one.
chgrp(filename, group) Assigns the named file to the named group.
chroot(directory) Makes the named directory the root directory.
chmod(filename, mode) Changes the mode of the named file.
chown(filename, owner) Changes the owner of the named file.
clearstatcache() Clears the file stat cache.
closedir(directory) Closes the named directory.
copy(source, destination) Copies the named source file to the named
destination.
dir(directory) Returns an object with the value of the named
directory.
dirname(path) Returns the directory listed in the named path.
Table continued on following page
717
PHP5 Functions
Function Description
disk_free_space(directory) Returns the amount of free space in the named
directory.
disk_total_space(directory) Returns the amount of space in the named
directory.
diskfreespace(directory) Equal to disk_free_space(), returns the
amount of free space in the named directory.
getcwd() Returns the name of the current directory.
fclose(file_pointer) Closes the named file.
feof(file_pointer) Verifies whether or not the end of file has been
reached for the named file.
fflush(file_pointer) Flushes the output to a file.
fgetc(file_pointer) Returns the next character listed in the named
file.
fgetcsv(file_pointer, length[, Returns the next line in the named file.
delimiter])
fgets(file_pointer, length) Returns a line of up to (length–1) in the named
file.
fegtss(file_pointer, length[, Returns a line of up to (length–1) in the named
allowable_tags]) file, while removing all tags except those
specified.
file(filename[, usepath]) Returns an entire file in an array format, with
each line representing a new value in the array.
file_get_contents(filename) Reads the entire file contents into a string.
file_exists(filename) Verifies whether the named file exists.
fileatime(filename) Returns the last time the named file was
accessed.
filectime(filename) Returns the last time the named file was
changed (in UNIX timestamp format).
filegroup(filename) Returns the owner of the named file’s group.
fileinode(filename) Returns the named file’s inode number.
filemtime(filename) Returns the last time the named file was
modified.
fileowner(filename) Returns the owner of the named file.
fileperms(filename) Returns the permissions associated with the
named file.
718
Appendix C
Function Description
filesize(filename) Returns the size of the named file.
filetype(filename) Returns the type of the named file.
flock(file_pointer, operation[, Locks or unlocks the named file.
wouldblock])
fnmatch(pattern, exp) Searches for a filename that matches the named
parameters.
fopen(filename, mode[, usepath]) Opens the named file.
fpassthru(file_pointer) Returns all remaining data in the named file.
fputs(file_pointer, string[, Equal to fwrite(), writes the named string to
length]) the named file.
fread(file_pointer, length) Reads the named file up to the named length.
fscanf(handle, format[, var1, Parses input based on the named format from
var2...]) the named file.
fseek(file_pointer, offset[, start]) Moves the file pointer in the named file by
named offset spaces from start.
fstat(file_pointer) Returns information about named file.
ftell(file_pointer) Returns the position of the file pointer in the
named file.
ftruncate(file_pointer, size) Truncates the named file to the named size.
fwrite(file_pointer, string Equal to fputs(), writes the named string to
[, length]) the named file.
glob(string) Finds path names that match the named string.
is_dir(filename) Verifies whether the named file is a directory.
is_executable(filename) Verifies whether the named file is an executable.
is_file(filename) Verifies whether the named file is a file.
is_link(filename) Verifies whether the named file is a link.
is_readable(filename) Verifies whether the named file is readable.
is_writeable(filename) Verifies whether the named file is writeable.
is_uploaded_file(filename) Verifies whether the named file has been
uploaded using HTTP POST.
link(target, link) Creates a new link.
linkinfo(path) Returns all information about the named link.
Table continued on following page
719
PHP5 Functions
Function Description
lstat(filename) Returns information about named file.
mkdir(pathname, mode) Creates a directory based on specified path
name and mode.
move_uploaded_file(filename, Moves the named file to a different directory.
destination)
opendir(path) Opens the named directory.
parse_ini_file(filename) Parses the named configuration file.
pathinfo(path) Returns information about the named path.
pclose(file_pointer) Closes the named file pointer to a pipe.
popen(command, mode) Opens a pipe with the named command.
readdir(directory) Reads the named directory and returns the next
entry.
readfile(filename[, usepath]) Reads the named file.
readlink(path) Reads the named link and returns the target.
realpath(path) Returns the absolute path.
rename(name, newname) Renames the named file.
rewind(file_pointer) Moves the pointer to the beginning of the file
stream.
rewinddir(directory) Moves the pointer to the beginning of the
directory and resets the directory stream.
rmdir(directory) Removes the named directory.
scandir(directory[, sort_order]) Lists the files and directories in the named path.
set_file_buffer(file_pointer, Sets the file buffer for named file.
buffer)
stat(filename) Returns information about the named file.
symlink(target, link) Creates a symbolic link.
tempnam(directory, prefix) Creates a temporary file in the named directory.
tmpfile() Creates a temporary file.
touch(filename[, time]) Sets the time the named file is modified.
umask(mask) Modifies the current umask.
unlink(filename) Deletes the named file.
720
Appendix C
Error Handling and Logging Functions
These functions can help you view and use errors to debug programs or alert you to potential problems
in your scripts.
Function Description
debug_backtrace() Generates a backtrace and returns the
information in an array format.
debug_print_backtrace() Displays a generated backtrace.
error_log(message, message_type[, Adds an error message to the server’s log, and
dest, extra_headers]) anywhere else depending on the message type
as defined in the given parameter. Message
type 0 sends a message to PHP’s system logger,
type 1 sends an e-mail to the address specified
in the dest parameter, type 2 sends a remote
debugging message to the IP address or
hostname specified in the dest parameter, and
type 3 appends the error message to the file
specified in the dest parameter.
error_reporting([level]) Determines which PHP errors will be
displayed.
restore_error_handler() Restores error handler functions.
restore_exception_handler(function) Restores an exception handler function.
set_error_handler(error_handler) Sets an error handler function.
set_exception_handler(function) Sets a user-defined exception handler function.
trigger_error(error_message[, Same as user_error(), displays a user-level
error_type]) error message.
user_error(error_message[, Same as trigger_error(), displays a
error_type]) user-level error message.
HTTP Functions
These functions work with the HTTP protocol.
Function Description
header(string) Outputs the named HTTP header.
headers_list() Returns an array containing the headers that
will be sent.
headers_sent() Verifies whether HTTP headers have been sent.
Table continued on following page
721
PHP5 Functions
Function Description
setcookie(name, [value, expiration, Sends a cookie to the user based on the named
path, domain, secure]) parameters.
setrawcookie(name, [value, Sends a cookie to the user without url
expiration, path, domain, secure]) encoding it first.
Image Functions
The following PHP functions enable you to manipulate and create images directly from your PHP code.
Please note that you may need to have the GD library, which enables you to create dynamic images,
installed to enable some of these functions. You can download GD from www.boutell.com/gd/.
Function Description
exif_imagetype(filename) Returns the type of named image file.
exif_read_data(filename) Reads the EXIF headers in a JPEG or TIFF
image, useful for reading digital images.
exif_thumbnail(filename[, width, Reads the embedded thumbnail image of a
height, type]) JPEG or TIFF image.
gd_info() Returns information about the currently
installed GD library.
getimagesize(filename, [image_info]) Returns the size of the named file.
image_type_to_mime_type(type) Gets the MIME-type for the named image type.
image2wbmp(image[, filename]) Outputs the image directly to a browser.
imagealphablending(image, blendmode) Sets the blending mode for the named image.
imageantialias(image, on_off) Toggles antialiasing on and off for the named
image.
imagearc(name, cx, cy, width, Draws a partial ellipse based on named
height, start, end, col) parameters.
imagechar(name, font, x, y, c, col) Draws a character horizontally based on
named parameters.
imagecharup(name, font, x, y, c, col) Draws a character vertically based on named
parameters.
imagecolorallocate(name, red, green, Allocates a color for the named image and
blue) returns an identifier.
imagecolorallocatealpha(name, red, Similar to imagecolorallocate(), except
green, blue, transparent) allows the color to display at a certain level of
transparency.
722
Appendix C
Function Description
imagecolorat(name, x, y) Indicates the color index of the pixel at the
named coordinates.
imagecolorclosest(name, red, green, Returns the closest color in the palette of the
blue) named image.
imagecolorclosestalpha(name, red, Similar to imagecolorclosest(), except takes
green, blue, alpha) into account the alpha (transparency) level.
imagecolorclosesthwb(name, red, Similar to imagecolorclosest(), except also
green, blue) looks at hue, whiteness, and blackness.
imagecolordeallocate(name, red, Opposite of imagecolorallocate(),
green, blue) deallocates the color for the named image.
imagecolorexact(name, red, green, Returns the exact color in the palette of the
blue) named image.
imagecolorexactalpha(name, red, Similar to imagecolorexact(), except takes
green, blue, alpha) into account the alpha level.
imagecolorresolve(name, red, green, Returns either the index of the exact color or
blue) the closest color available in the palette of the
named image.
imagecolorresolvealpha(name, red, Similar to imagecolorresolve(), except
green, blue, alpha) takes into account the alpha level.
imagecolorset(name, index, red, Sets the color for the palette of the named file.
green, blue)
imagecolorsforindex(name, index) Returns value for red, blue, and green for the
specified index.
imagecolorstotal(name) Returns the number of available colors in the
palette of the named image.
imagecolortransparent(name[, color]) Sets the named color as transparent in the
named image.
imagecopy(dest_name, source_name, Copies an image based on named parameters.
dest_x, dest_y, source_x, source_y,
source_width, source_height)
imagecopymerge(dest_name, Similar to imagecopy(), but copies an image
source_name, dest_x, dest_y, based on named parameters including percent
source_x, source_y, source_width, (when set to 100, acts identically to
source_height, pct) imagecopy()).
imagecopymergegray(dest_name, Similar to imagecopymerge(), except copies
source_name, dest_x, dest_y, image in grayscale.
source_x, source_y, source_width,
source_height, pct)
Table continued on following page
723
PHP5 Functions
Function Description
imagecopyresampled(dest_name, Copies and resizes a resampled image based
source_name, dest_x, dest_y, on the named parameters.
source_x, source_y, dest_width,
dest_height, source_width,
source_height)
imagecopyresized(dest_name, Copies and resizes an image based on named
source_name, dest_x, dest_y, parameters.
source_x, source_y, dest_width,
dest_height, source_width,
source_height)
imagecreate(width, height) Creates a new image based on named width
and height.
imagecreatefromgd2(name) Creates a new image from a GD file or URL.
imagecreatefromgd2part(name, x, y, Creates a new image from a part of a GD file or
width, height) URL.
imagecreatefromgd(name) Creates a new image from a GD file or URL.
imagecreatefromgif(name) Creates a new image from the named GIF file.
imagecreatefromjpeg(name) Creates a new image from the named JPEG or
JPG file.
imagecreatefrompng(name) Creates a new image from the named PNG file.
imagecreatefromstring(name) Creates a new image from an image stream in
the named string.
imagecreatefromwbmp(name) Creates a new image from named file or URL.
imagecreatefromxbm(name) Creates a new image from named file or URL.
imagecreatefromxpm(name) Creates a new image from named file or URL.
imagecreatetruecolor(x_size, y_size) Returns an image identifier based on a black
image according to the named parameters.
imagedestroy(name) Deletes the named image.
imageellipse(name, cx, cy, width, Draws an ellipse based on the named
height, color) parameters.
imagefill(name, x, y, color) Fills the entire image with one color based on
the named parameters.
imagefilledarc(name, cx, cy, width, Draws a filled partial ellipse based on the
height, start, end, color, style) named parameters.
imagefilledellipse(name, cx, cy, Draws a filled ellipse based on the named
width, height, color) parameters.
724
Appendix C
Function Description
imagefilledpolygon(name, points, Draws a filled polygon based on the named
num_of_points, color) parameters.
imagefilledrectangle(name, x1, y1, Draws a filled rectangle based on the named
x2, y2, color) parameters.
imagefilltoborder(name, x, y, Fills the entire image with a color and outlines
border_color, color) it with a border color, based on named
parameters.
imagefontheight(font) Returns the height of the named font in pixels.
imagefontwidth(font) Returns the width of the named font in pixels.
imagegammacorrect(name, inputgamma, Corrects the gamma levels in a GD image.
outputgamma)
imagegd2(name[, filename, Outputs the named GD file to the browser
chunk_size, type]) based on the named parameters.
imagegd(name[, filename]) Sends the named GD file to the browser.
imagegif(name[, filename]) Sends the named GIF image to another file or
to a browser as the named image.
imageinterlace(name[, interlace]) Toggles whether interlacing is on or off for the
named image.
imageistruecolor(name) Returns whether or not an image is truecolor.
imagejpeg (name[, filename, Sends the named JPEG image to another file or
quality]) to a browser as the named image.
imageline(name, x1, y1, x2, y2, Draws a solid line based on the named
color) parameters.
imageloadfont(filename) Loads the named font.
imagepallettecopy(destination, Copies the named color palette.
source)
imagepng(name[, filename]) Sends the named PNG image to another file or
to a browser as the named image.
imagepolygon(name, points, Draws an empty polygon based on the named
num_of_points, color) parameters.
imagepsbbox(text, font, size, space, Returns the coordinates for a text box using a
width, angle) PostScript font, based on named parameters.
imagepscopyfont(font_index) Makes a copy of an already loaded PostScript
font.
imagepsencodefont(encoding_file) Loads the named encoding vector for a
PostScript font.
Table continued on following page
725
PHP5 Functions
Function Description
imagepsextendfont(font_index, extend) Extends a PostScript font.
imagepsfreefont(font_index) Frees the named PostScript font from memory.
imagepsloadfont(filename) Loads the named PostScript font file.
imagepsslantfont(font_index, slant) Slants the named PostScript font.
imagepstext(name, text, font, size, Writes a text string using the named PostScript
foreground_color, background_color, font and based on the named parameters.
x, y[, space, tightness, angle,
antialias])
imagerectangle(name, x1, y1, x2, y2, Draws an empty rectangle based on the named
color) parameters.
imagerotate(name, angle, color) Rotates an image based on the named
parameters.
imagesavealpha(name, flag) Sets the flag to save with the image’s alpha
information.
imagesetbrush(name, brush) Sets the brush for line drawing.
imagesetpixel(name, x, y, color) Draws a pixel based on the named parameters.
imagesetstyle(name, style) Sets the style for line drawing.
imagesetthickness(name, thickness) Sets the thickness for line drawing.
imagesettile(name, tile) Sets the tile image for fill functions.
imagestring(name, font, x, y, Draws a horizontal string based on the named
string, color) parameters.
imagestringup(name, font, x, y, Draws a vertical string based on the named
string, color) parameters.
imagesx(name) Determines the width of the named image.
imagesy(name) Determines the height of the named image.
imagetruecolortopallette(name, Converts a true color image to a color palette
dither, colors) based on the named parameters.
imagettfbbox(size, angle, Draws a text box using the named TrueType
font_filename, text) font and based on the named parameters.
imagettftext(name, size, angle, x, Writes a text string using the named TrueType
y, color, font_filename, text) font.
imagetypes() Displays the image types supported by the
PHP version currently being used.
iptcembed(data, filename) Embeds International Press Telecommunications
Council (IPTC) data into a JPEG file.
726
Appendix C
Function Description
iptcparse(iptcblock) Parses an IPTC block into tags.
jpeg2wbmp(jpegfilename, wbmpfilename, Converts a JPEG file into a WBMP file.
height, width, threshold)
png2wbmp(pngfilename, wbmpfilename, Converts a PNG file into a WBMP file.
height, width, threshold)
read_exif_data(filename) Displays any EXIF headers from a JPEG file.
Mail Functions
Use these functions to send mail directly from your PHP script.
Function Description
ezmlm_hash(addr) Displays the hash value used by EZMLM
scripts.
mail(to, subject, message[, headers]) Sends mail based on the named parameters.
Mathematical Functions
These functions allow you to perform mathematical calculations on your data while still in the PHP code.
Function Description
abs(number) Calculates the absolute value of a number.
acos(argument) Calculates the arc cosine in radians.
asin(argument) Calculates the arc sine in radians.
atan(argument) Calculates the arc tangent in radians.
atan2(x, y) Calculates the arc tangent of x and y.
base_convert(number, Converts a number based on the named parameters.
startbase, endbase)
bindec(binary_string) Converts a binary string to a decimal, the opposite of
decbin().
ceil(number) Rounds fractions to next highest integer.
cos(argument) Calculates the cosine in radians.
decbin(number) Converts a decimal to a binary string, the opposite of
bindec().
Table continued on following page
727
PHP5 Functions
Function Description
dechex(number) Converts a decimal to hexadecimal, the opposite of
hexdec().
decoct(number) Converts a decimal to octal, the opposite of octdec().
deg2rad(number) Converts degrees to radian, opposite of rad2deg().
exp(argument) Calculates e to the named power.
floor(number) Rounds fractions down to the next lowest integer.
fmod(num1, num2) Returns the floating point remainder of the division of the
two numbers.
getrandmax() Calculates the maximum random value from the rand()
function.
hexdec(hex_string) Converts hexadecimal to decimal, opposite of dechex().
is_finite(number) Returns whether or not the number is a finite number.
is_infinite(number) Returns whether or not the number is an infinite number.
is_nan(number) Returns whether or not the number is truly a number.
lcg_value() Calculates a pseudo-random number between 0 and 1.
log(argument) Calculates the natural log.
log10(argument) Calculates the base 10 log.
max(num1, num2, ...) Calculates the maximum of listed values.
min(num1, num2, ...) Calculates the minimum of listed values.
mt_getrandmax() Calculates the maximum random value from the
mt_rand() function.
mt_rand([min, max]) Generates a Mersenne Twister random value.
mt_srand(seed) Seeds the Mersenne Twister random number generator.
number_format(number[, Formats the number based on the named parameters.
dec_places, dec_point,
thousands])
octdec(octal_string) Converts octal to decimal, the opposite of decoct().
pi() Returns pi to the number of digits set in the php.ini file.
pow(number, exp) Calculates named number to the power of named exponent.
rad2deg(number) Converts radians to decimal, the opposite of deg2rad().
rand([min, max]) Generates a random integer based on named parameters if
applicable.
round(number, [precision]) Rounds the named number to the nearest integer.
728
Appendix C
Function Description
sin(argument) Calculates the sine in radians.
sqrt(argument) Calculates the square root.
srand(seed) Seeds the random number generator.
tan(argument) Calculates the tangent in radians.
MySQL Functions
The following table lists the PHP functions that can be used with your MySQL server for added functionality
in your PHP script.
Function Description
mysql_affected_rows([link_id]) Returns the number of rows of records
affected by the previous command.
mysql_client_encoding() Returns the character set used by the current
connection.
mysql_close([link_id]) Closes the active connection.
mysql_connect([hostname[:port] Opens the connection to the server based
[:/path/to/socket], username, on the named parameters. Similar to
password]) mysql_pconnect().
mysql_data_seek(result_id, row_number) Moves to the named row of the results.
mysql_db_name(result, row [,field]) Gets data for result.
mysql_db_query(database, query[, Executes the named query on the named
link_id]) database and returns results.
mysql_errno([link_id]) Displays the error number for the previous
query.
mysql_error([link_id]) Displays the error message for the previous
query.
mysql_escape_string(string) Escapes the named string for use in a query.
mysql_fetch_array(result [, type]) Obtains the row of data based on the result
from a previous query, returns result in an
array format.
mysql_fetch_assoc(result) Returns an associative array based on the
query previously sent to the server.
mysql_fetch_field(result[, Returns the field based on the result from a
field_offset]) previous query.
Table continued on following page
729
PHP5 Functions
Function Description
mysql_fetch_lengths(result) Returns the length of each field in the result
from a previous query.
mysql_fetch_object(result[, type]) Obtains data based on the result from a
previous query, returns result in an object
format.
mysql_fetch_row(result) Obtains the row of data based on the result
from a previous query, returns result in an
enumerated array.
mysql_field_flags(result, field) Displays the field flag of the named field.
mysql_field_len(result, field) Displays the field length of the named field.
mysql_field_name(result, field) Displays the name of the named field.
mysql_field_seek(result, field_offset) Moves to the named field of the results.
mysql_field_table(result, field) Displays the table of the named field.
mysql_field_type(result, field) Displays the type of the named field.
mysql_free_result(result) Frees any memory still used by the result
from a previous query.
mysql_get_client_info() Returns the MySQL client information.
mysql_get_host_info([link_id]) Returns information about the server host.
mysql_get_proto_info([link_id]) Returns the protocol information.
mysql_get_server_info([link_id]) Returns information about the server.
mysql_info([link_id]) Gets information about the previous query.
mysql_insert_id([link_id]) Returns the ID value of the most recently
inserted auto_increment field.
mysql_list_dbs([link_id]) Lists the databases on the MySQL server.
mysql_list_fields(database, Lists the fields in the named database and
table[, link_id]) table.
mysql_list_processes([link_id]) Lists the processes.
mysql_list_tables(database) Lists the tables in the named database.
mysql_num_fields(result) Shows the number of fields in the result
from a previous query.
mysql_num_rows(result) Shows the number of rows in the result from
a previous query.
mysql_pconnect([hostname[:port] Opens a persistent connection to the server
[:/path/to/socket], username, based on the named parameters. Similar to
password]) mysql_connect().
730
Appendix C
Function Description
mysql_ping([link_id]) Pings the server connection to verify the
connection is working properly.
mysql_query(query[, link_id]) Executes the named query.
mysql_real_escape_string(string[, Escapes a string to be used in the query,
link_id]) and takes into account the charset of the
connection.
mysql_result(result, row[, field]) Obtains the data located in the named field/
row of the results.
mysql_select_db(database[, link_id]) Selects the named database and makes it
current.
mysql_stat([link_id]) Gets the current system status.
mysql_thread_id([link_id]) Returns current connection thread ID.
mysql_tablename(result, index) Returns the table from which the result was
obtained.
mysql_unbuffered_query(query[, Queries the MySQL server without fetching
link_id]) and buffering the results.
Network Functions
The functions in the table that follows can be used to communicate with your network directly from PHP.
Function Description
checkdnsrr(host[, type]) Equal to dns_check_record(), searches for DNS
records based on the named parameters.
closelog() Closes the connection to the system log, the opposite
of openlog().
define_syslog_variables() Initializes syslog constants.
dns_check_record(host[, type]) Equal to checkdnsrr(), searches for DNS records
based on named parameters.
dns_get_mx(host, mxhosts[, Equal to getmxrr(), returns MX records based on
weight]) the named host.
dns_get_record(host[, type) Gets DNS records associated with the hostname.
fsockopen([hostname, port, Opens a socket connection based on the named
errno, errstr, timeout]) parameters.
gethostbyaddr(ip) Returns the hostname based on the named IP
address.
Table continued on following page
731
PHP5 Functions
Function Description
gethostbyname(host) Returns the IP address based on the named host.
gethostbyname1(host) Returns multiple IP addresses based on the named
host.
getmxrr(host, mxhosts[, weight]) Equal to dns_get_mx(), returns MX records based
on the named host.
getprotobyname(name) Returns protocol number based on named protocol.
getprotobynumber(number) Returns protocol name based on named protocol
number.
getservbyname(service, protocol) Returns a port number based on named parameters.
getservbyport(port, protocol) Returns the service based on named parameters.
ip2long(ip) Converts a string with an IP address into a proper
address.
long2ip(proper_address) Converts a proper address into an IP address with
dotted format.
openlog(ident, option, facility) Opens a connection to the system log, the opposite
of closelog().
pfsockopen([hostname, port, Opens a persistent socket connection based on the
errno, errstr, timeout]) named parameters.
syslog(priority, message) Writes the named message to the system log.
Output Buffer Functions
The functions in the table that follows enable you to control the output buffer from PHP.
Function Description
flush() Flushes the output buffer.
ob_clean() Destroys the contents of the output buffer.
ob_end_flush() Sends the output buffer contents and disables
output buffering.
ob_end_clean() Deletes the output buffer contents and disables
output buffering.
ob_flush() Sends the output buffer.
ob_get_clean() Gets the contents of the output buffer and
deletes the output buffer.
ob_get_contents() Gets the contents of the output buffer.
732
Appendix C
Function Description
ob_get_length() Gets the length of the output buffer.
ob_get_level() Gets the nesting level of the output buffer.
ob_gzhandler() Callback function to gzip the output buffer.
ob_implicit_flush() Toggles implicit flushing on and off.
ob_list_handlers() Returns all output handlers being used.
ob_start() Enables output buffering.
output_add_rewrite_var(name, value) Adds values to URLs.
output_reset_rewrite_vars() Resets any values added to URLs from the
output_add_rewrite_var() function.
PHP Configuration Information
With these functions, you can easily determine what your PHP is communicating to the server based on
its setup, and alter configuration options from your PHP script.
Function Description
assert(assertion) Verifies whether an assertion is false.
assert_options(what,[ value]) Returns the assert flags.
extension_loaded(name) Verifies whether or not an extension library has
been loaded.
get_cfg_var(var) Returns the named configuration variable value.
get_current_user() Returns the owner of the PHP script.
get_defined_constants() Returns an array with all the defined constants
and their values.
get_extension_funcs(module_name) Returns the functions in the named module.
get_include_path() Returns the current include_path
configuration option.
get_included_files() Returns an array containing the filenames of
those included or required in the script.
get_loaded_extensions() Returns the compiled and loaded modules.
get_magic_quotes_gpc() Returns the setting of magic_quotes_gpc.
get_magic_quotes_runtime() Returns the setting of magic_quotes_runtime.
get_required_files() Returns an array containing the filenames of
those included or required in the script.
Table continued on following page
733
PHP5 Functions
Function Description
getenv(var) Returns the value of the named environment
variable.
getlastmod() Returns when the page was last modified.
getmygid() Returns the group ID for the current script.
getmyinode() Returns the inode of the script.
getmypid() Returns the process ID for PHP.
getmyuid() Returns the user ID for the owner of the PHP
script.
getopt() Returns an array of options/argument pairs
from the command-line argument list.
getrusage([who]) Returns resource usage.
ini_alter(varname, newvalue) Updates the php.ini file based on the named
parameters.
ini_get_all([extension]) Returns configuration options.
ini_get(varname) Returns the named value from the php.ini file.
ini_restore(varname) Restores the previous value in the php.ini file.
ini_set(varname, newvalue) Sets the named value in the php.ini file.
memory_get_usage() Returns the amount of memory allocated to
PHP.
php_ini_scanned_files() Returns a list of parsed ini files from an
additional directory.
php_logo_guid() Returns the PHP logo GUID.
php_sapi_name() Returns the interface between the Web server
and PHP.
php_uname() Returns information about the operating
system running PHP.
phpcredits(flag) Displays the credits for PHP.
phpinfo() Displays information about the current
environment and configuration of PHP.
phpversion() Displays the currently running PHP version.
putenv(setting) Sets the value of an environment variable.
restore_include_path() Restores the include_path configuration
option.
734
Appendix C
Function Description
set_include_path(path) Sets the include_path configuration option.
set_magic_quotes_runtime(newsetting) Turns the magic quotes feature on or off.
set_time_limit(seconds) Sets the maximum amount of time a PHP script
can run.
version_compare(string1, string2) Compares two PHP version numbers.
zend_logo_guid() Returns the Zend logo GUID.
zend_version() Returns the current Zend engine.
Program Execution Functions
The functions in the table that follows allow PHP code to execute commands directly from the script.
Function Description
escapeshellarg(arg) Escapes a string to be used as a shell argument.
escapreshelllcmd(cmd) Escapes shell metacharacters in the named command.
exec(command[, array, Executes the named command and returns the last
return_var]) line of results.
passthru(command[, return_var]) Executes the named command and returns the raw
output.
proc_close(process) Closes processes opened by the proc_open()
function.
proc_get_status(process) Gets information about a process opened by the
proc_open() function.
proc_nice(number) Changes the priority of the current process according
to the supplied number.
proc_open(string cmd, array Executes the given command according to the given
descriptorspec, array &pipes parameters.
[, string cwd [, array env
[, array other_options)]]])
proc_terminate(process) Terminates a process opened by the proc_open()
function.
shell_exec(command) Executes a command through the shell.
system(command[, return_var]) Executes the named command and returns all the
output.
735
PHP5 Functions
Spelling Functions
You can have PHP perform spell checks for you, as long as you supply a reference it can use.
Function Description
pspell_add_to_personal(link, word) Adds the named word to a personal dictionary.
pspell_add_to_session(link, word) Adds the named word to a session’s wordlist.
pspell_check(link, word) Using the named link as a reference, it will check
the spelling of the named word.
pspell_clear_session() Deletes a current session’s wordlist.
pspell_config_create(language[, Configures options to open a dictionary.
spelling, jargon, encoding])
pspell_config_ignore(link, n) Configures spell check so that words under n
characters long will be ignored.
pspell_config_mode(link, mode) Changes the number of suggestions offered.
pspell_config_personal(link, file) Sets the file that will contain a personal wordlist.
pspell_config_repl(link, file) Sets the file that contains replacement pairs.
pspell_config_runtogether(link, Determines if run-together words are valid.
flag)
pspell_config_save_repl(link, Determines if replacement pairs should be saved
flag) with the personal wordlist.
pspell_new_config() Loads a new dictionary based on the supplied
config.
pspell_new_personal() Loads a new personal wordlist based on the
supplied config.
pspell_new(language[, spelling, Loads a new dictionary with a personal wordlist.
jargon, encoding, mode])
pspell_save_wordlist(link) Saves the personal wordlist to the named link.
pspell_store_replacement(link, Stores a replacement pair for a word.
misspelled, correct)
pspell_suggest(link, word) Suggests a list of alternatives for the named word.
Session Functions
The functions in the table that follows are useful when utilizing sessions in your PHP scripts.
736
Appendix C
Function Description
session_cache_expire([new_cache_expire]) Returns the cache expiration, or sets a
new one (in minutes).
session_cache_limiter([cache_limiter]) Returns the cache limiter, or sets a
new one.
session_commit() Equal to session_write_close(), this
ends the current session and stores all
session variables.
session_decode(string) Decodes the named session data.
session_destroy() Destroys session data.
session_encode() Encodes session data as a string.
session_get_cookie_params() Gets information about session cookie
configuration.
session_id([id]) Returns the session ID, or sets a new one.
session_is_registered(varname) Verifies whether the named variable has
been registered in current session.
session_module_name([module_name]) Returns the session module, or sets a
new one.
session_name([name]) Returns the session name, or sets a
new one.
session_regenerate_id() Generates a new session ID for the current
session and maintains session variables
and their contents.
session_register(name[,var1, var2...]) Registers variables with the current
session.
session_save_path([path]) Returns the path where session data is
saved, or sets a new one.
session_set_cookie_params(expiration[, Configures the session cookie based on
path, domain]) the named parameters.
session_set_save_handler(open, close, Sets user-level session storage based on
read, write, destroy, gc) named parameters.
session_start() Starts a new session.
session_unregister(name) Unregisters session variables.
session_unset() Releases all session variables.
session_write_close() Ends the current session and stores all
session variables.
737
PHP5 Functions
String Functions
There are times when you need PHP to manipulate strings for you, and luckily many functions help you
do just that.
Function Description
addcslashes(string, charlist) Adds slashes before named characters in the
named string.
addslashes(string) Adds slashes to quoted characters in the named
strings for database queries.
bin2hex(string) Converts binary data into ASCII hexadecimal
format.
chop(string) Equal to rtrim(), deletes trailing spaces from
the named string.
chr(ascii) Returns the character based on the named ASCII
code.
chunk_split(string[, length, div]) Divides the named string by inserting the
character named by div every length characters.
convert_cyr_string(string, Converts the named string from one Cyrillic
from, to) character set to another.
convert_uudecode(string) Converts a string encoded with the
convert_uuencode() function.
convert_uuencode(string) Encodes a string using the uuencode algorithm.
count_chars(string[, mode]) Counts the number of characters in the named
string.
crc32(string) Calculates the crc32 of 32-bit lengths of string.
crypt(string[, char]) Using named 2-character parameter, this will
DES-encrypt the named string.
echo(string) Displays the named string.
ereg(exp, string[, array]) Searches the named string for the named
expression and stores the results in the named
array.
ereg_replace(exp1, exp2, string) Searches and replaces exp1 with exp2 in the
named string.
eregi(exp, string[, array]) Searches the named string for the named
expression (case-insensitive) and stores the
results in the named array.
eregi_replace(exp1, exp2, string) Searches and replaces exp1 with exp2
(case-insensitive) in the named string.
738
Appendix C
Function Description
explode(separator, string[, limit]) Divides the named string using the named
separator and returns results in array format, the
opposite of implode().
fprintf(res handle, format) Sends a formatted string to a stream.
get_html_translation_table(table[, Returns the named translation table.
quote_styles])
hebrev(text[, max_chars_per_line]) Converts Hebrew text to visual text.
hebrevc(text[, max_chars_per_line]) Converts Hebrew text to visual text with
newlines.
html_entity_decode(string[, The opposite of htmlentities(), converts
quote style]) HTML entities into their applicable characters.
htmlentities(string[, quote_style]) Converts characters from the named string into
HTML entities.
htmlspecialchars(string[, Converts special characters from the named
quote_style]) string into HTML entities.
implode(delimiter, array_name) The opposite of explode(), this combines bits
of the named array together using the named
delimiter tag, equal to join().
join(delimiter, array_name) Equal to implode(), this combines bits of the
named array together using the named delimiter
tag.
levenshtein(str1, str2) Calculates the Levenshtein distance between the
two named strings.
localeconv() Returns an array with local monetary and
numeric formatting information.
ltrim(string) Deletes spaces from the beginning of the named
string.
md5_file(filename) Calculates the MD5 hash of the named file.
md5(string) Calculates the MD5 hash of the named string.
metaphone(string) Calculates the metaphone key of the named string.
money_format(format, number) Formats the number as a currency.
nl_langinfo(item number) Returns specific information about the local
language and numeric/monetary formatting.
nl2br(string) Inserts the HTML code for
before all line
breaks in the named string.
Table continued on following page
739
PHP5 Functions
Function Description
number_format(number, decimals) Formats the number based on the named
parameters.
ord(string) Returns the ASCII code of the first character in
the named string.
parse_str(string[, array]) Parses the string and stores the results in the
named array.
print(string) Displays the string and returns a value of 1.
printf(format[, arg1, arg2, ...]) Displays a formatted string based on the named
parameters.
quoted_printable_decode(string) Converts a quoted-printable string to an 8-bit
string.
quotemeta(string) Escapes metacharacters in the named string.
rtrim(string) Deletes trailing spaces from the end of the named
string.
setlocale(category, locale) Sets the locale information for functions in the
named category.
sha1_file(filename[, output]) Calculates the sha1 hash for a file.
sha1(string[, output]) Calculates the sha1 hash for a string.
similar_text(string1, Determines the similarity between two named
string2[, percent]) strings.
soundex(string) Determines the soundex key of the named string.
split(exp, string[, limit]) Splits the named string using the named
expression.
spliti(exp, string[, limit) Splits the named string using the named
expression (case-insensitive).
sprintf(format[, arg1, arg2...]) Displays the formatted string based on the
named parameters.
sql_regcase(string) Searches the named string (case-insensitive) and
returns a regular expression.
sscanf(string, format[, var1, Parses input from the named string based on the
var2...]) named parameters.
str_ireplace(oldexp, newexp, Similar to str_replace(), except it is casestring)
insensitive.
str_pad(string, length[, Pads the named string to the named length with
pad_string, pad_type]) another string.
str_repeat(string, number) Repeats a named string a named number of times.
740
Appendix C
Function Description
str_replace(oldexp, newexp, string, Replaces one expression with another in the
[count]) named string, and optionally returns the number
of changes made.
str_rot13(string) Performs the ROT13 encoding on the named
string.
str_shuffle(string) Randomly shuffles the string.
str_split(string[, length]) Converts a string into an array based on the
optional length parameter.
str_word_count(string[, format]) Counts the number of words in the string.
strcasecmp(string1, string2) Compares two named strings, case-insensitive.
strchr(string, exp) Locates the named expression in the named
string, equal to strstr().
strcmp(string1, string2) Similar to strcasecmp(), except comparison is
case-sensitive.
strcoll(string1, string2) Compares the two strings based on locale.
strcspn(string1, string2) Returns the number of characters at the
beginning of string1 that do not match
string2, opposite of strspn().
strip_tags(string) Removes HTML and PHP tags from the named
string.
stripcslashes(string) Removes C slashes from the named string.
stripos(str1, str2) Finds the position of the first occurrence of str2
in str1; case-insensitive.
stripslashes(string) Removes escaped slashes from the named string.
stristr(string, exp) Finds all occurrences of the named expression in
the named string (case-insensitive).
strlen(string) Returns the length of the named string.
strnatcasecmp(string1, string2) Compares two named strings using “natural
order” (case-insensitive).
strnatcmp(string1, string2) Compares two named strings using “natural
order.”
strncasecmp(string1, string2, n) Compares the first n characters of the two named
strings (case-insensitive).
strncmp(string1, string2, n) Compares the first n characters of the two named
strings.
Table continued on following page
741
PHP5 Functions
Function Description
strpbrk(string1, char_list) Searches string1 for any of the characters in the
named character list.
strpos(string, exp) Returns the numerical position of the first
occurrence of the named expression in the named
string.
strrchr(string, exp) Locates the last occurrence of the named
expression in the named string.
strrev(string) Reverses the named string.
strripos(string, exp) Returns the numerical position of the last
occurrence of the named expression in the named
string (case-insensitive).
strrpos(string, exp) Returns the numerical position of the last
occurrence of the named expression in the named
string.
strspn(string1, string2) Returns the number of characters at the
beginning of string1 that match string2, the
opposite of strcspn().
strstr(string, exp) Finds all occurrences of a named expression in a
named string (case-sensitive).
strtok(string1, string2) Tokenizes named string based on named
parameter, string2.
strtolower(string) Converts the named string to lowercase
characters.
strtoupper(string) Converts the named string to uppercase
characters.
strtr(string, exp1, exp2) Translates characters based on the named
parameters.
substr(string, start[, num_char]) Returns the named number of characters from
the named start position in the named string.
substr_compare(string1, string2, Compares two strings from a given offset with
offset[, length, [,case]]) the option of case-insensitivity.
substr_count(string, exp) Returns the number of occurrences of the named
expression in the named string.
substr_replace(string, replacement, Replaces text within the named string based on
start[, num_char]) the named parameters.
trim(string) Deletes extra space at the beginning and end of
the named string.
742
Appendix C
Function Description
ucfirst(string) Converts the first character to uppercase.
ucwords(string) Converts the first character of each word to
uppercase.
vfprintf(stream, format, arguments) Sends the formatted string to a stream.
vprintf(format, arguments) Displays a formatted string.
vsprintf(format, arguments) Returns a formatted string as an array.
wordwrap(string[, width, break, Wrap the string based on the named parameters,
cut]) using the named break character.
URL Functions
The functions in the table that follows allow you to handle URLs within your PHP code.
Function Description
base64_decode(string) Decodes an encoded string, the opposite of
base64_encode().
base64_encode(string) Encodes a string, the opposite of base64_decode().
get_headers(url) Gets the headers sent by the server.
get_meta_tags(filename/url) Extracts and returns all meta tag information in a given file
or URL.
http_build_query(formdata[, Creates a URL-encoded query string based on data
prefix]) contained in an array.
parse_url(url) Parses the URL into components.
rawurldecode(string) Decodes a URL-encoded string, the opposite of
rawurlencode().
rawurlencode(string) URL-encodes a string, the opposite of rawurldecode().
urldecode(string) Decodes an encoded string, the opposite of urlencode().
urlencode(string) Encodes a string, the opposite of urldecode().
Variable Functions
Variables are a common tool used in PHP, and there are numerous functions to increase your ability to
manipulate them.
743
PHP5 Functions
Function Description
doubleval(var) Doubles the value of the variable.
empty(var) Verifies whether the variable exists and has a nonzero
value.
floatval(var) Returns the float value of a variable.
get_defined_vars() Returns all the defined variables in a script.
get_resource_type(handle) Returns the resource type.
gettype(var) Shows the field type of the variable.
import_request_variable(types[, Imports GET/POST/Cookie variables into the global
prefix]) scope.
intval(var[, base]) Returns the integer value of the variable, using the
named base.
is_array(var) Verifies whether the variable is an array.
is_bool(var) Verifies whether the variable is Boolean.
is_callable(var) Verifies whether the variable can be called as a
function.
is_double(var) Verifies whether the variable is a double.
is_float(var) Verifies whether the variable is a float.
is_int(var) Equal to is_integer() and is_long(), verifies
whether the variable is an integer.
is_integer(var) Equal to is_int() and is_long(), verifies whether
the variable is an integer.
is_long(var) Equal to is_int() and is_integer(), verifies
whether the variable is an integer.
is_null(var) Verifies whether the variable is null.
is_numeric(var) Verifies whether the variable is a number or numeric
string.
is_object(var) Verifies whether the variable is an object.
is_real(var) Verifies whether the variable is a real number.
is_resource(var) Verifies whether the variable is a resource.
is_scalar(var) Verifies whether the variable is a scalar.
is_string(var) Verifies whether the variable is a string.
isset(var) Verifies whether the variable has been assigned a
value.
744
Appendix C
Function Description
print_r(exp[, return]) Displays readable information about a variable.
serialize(value) Generates a storable version of variable.
settype(var, type) Sets the named variable to the named type.
strval(var) Returns the string value of the named variable.
unserialize(string) Generates a PHP value from a stored version.
unset(var) Deletes the named variable.
var_dump(exp) Displays information about the named expression.
var_export(exp) Outputs a string representation of the variable.
Miscellaneous Functions
The table that follows lists useful functions that don’t exactly fit anywhere else.
Function Description
connection_aborted() Verifies whether or not the client connection has been
aborted.
connection_status() Verifies the client connection status.
connection_timeout() Verifies whether or not the script has timed out.
constant(name) Returns the value of the named constant.
define(name, value[, Defines a constant based on the named parameters.
case_insensitive])
defined(name) Verifies whether or not a named constant exists.
die(message) Displays the message and ends execution of the script.
eval(string) Evaluates the named string as PHP code.
exit() Ends execution of the script.
get_browser([user_agent]) Returns information about the user’s browser.
highlight_file(filename) Displays a highlighted version of the named file.
highlight_string(str) Displays a highlighted version of the named string.
ignore_user_abort([setting]) Allows a script to continue executing if the user aborts
a connection.
pack(format[, arg1, arg2...]) Packs the named arguments into a binary string.
php_check_syntax(filename) Checks the syntax of the named file.
Table continued on following page
745
PHP5 Functions
Function Description
php_strip_whitespace(filename) Returns the source code of the named file with
comments and extra lines removed.
show_source(filename) Displays a highlighted version of source code of
named file.
sleep(seconds) Pauses execution of the script for a named number of
seconds.
time_nanosleep(seconds, Pauses execution of the script for a named number of
nanoseconds) seconds and nanoseconds.
uniqid(prefix[, lcg]) Assigns a unique ID based on the current time and
named prefix.
unpack(format, data) The opposite of pack(), this unpacks binary data into
an array.
usleep(microseconds) Pauses execution of the script for the named number
of microseconds.
746
Appendix C
D
MySQL Data Types
See the table that follows for the potential data or field types in MySQL.
MySQL Field Type Description
bigint(length) Numeric field that stores integers from
-9223372036854775808 to 9223372036854775807.
(Adding the unsigned parameter allows storage
of 0 to 18446744073709551615.) The parameter
length limits the number of characters to
be displayed. Please refer to the manual at
http://www.mysql.com before performing
mathematical calculations involving the bigint
type.
bit Equal to tinyint(1) field. A value of zero
represents false; a non-zero value represents
true.
blob Equal to a text field, except it is case-sensitive
when sorting and comparing. Stores up to 65535
characters.
bool Equal to tinyint(1) field. A value of zero
represents false; a non-zero value represents
true.
boolean Equal to tinyint(1) field. A value of zero
represents false; a non-zero value represents
true.
Table continued on following page
MySQL Field Type Description
char(length) Any characters can be in this field, but the field will
have a fixed length. The length parameter can be
between 0 and 255. If the length parameter is not
defined, the default value is 1. Adding the BINARY
attribute will make comparisons and sorting results
case-sensitive.
date Stores a date as yyyy-mm-dd. Allows values from
1000-01-01 to 9999-12-31.
datetime Stores date and time as yyyy-mm-dd hh:mm:ss.
Allows values from 1000-01-01 00:00:00 to 9999-12-31
23:59:59.
dec(length,dec) Equal to decimal field.
decimal(length,dec) Numeric field that can store decimals. The length
parameter limits the number of digits that will be
displayed, and the dec parameter limits the number
of decimal places that can be stored. The length
parameter does not count decimal points and “-” for
negative values. A price field that would store prices
up to 999.99, for example, would be defined as
decimal(5,2). If the length parameter is not specified,
the default is 10. Adding the unsigned attribute
allows only non-negative values.
double(length,dec) Amedium-sized floating point number that stores
values from -1.7976931348623157E+308 to
-2.2250738585072014E-308, 0, and
2.2250738585072014E-308 to 1.7976931348623157E+308.
The length parameter determines how many digits
will be displayed; the dec parameter determines how
many decimal places are displayed. (Adding the
unsigned parameter allows only positive numbers
to be stored.) Using double without parameters
specified represents a double-precision floating point
number.
double precision(length, dec) Equal to double.
enum(“option1”, “option2”, ...) Allows only certain values to be stored in this field,
such as true and false, or a list of states. 65,535
different options can be allowed.
fixed(length,dec) Equal to decimal field.
748
Appendix D
MySQL Field Type Description
float(length,dec) A small floating point number that stores values
from -3.402823466E+38 to -1.175494351E-38, 0, and
1.175494351E-38 to 3.402823466E+38. The length
parameter determines how many digits will be
displayed; the dec parameter determines how many
decimal places are displayed. (Adding the unsigned
parameter allows only positive numbers to be stored.)
float(precision) Equal to float(length,dec) except the length
and dec parameters are undefined. To be used with a
true floating point number. (Adding the unsigned
parameter allows only positive numbers to be stored.)
The precision parameter can be from 0 to 24 for
single-precision floating point numbers, and from
25-35 for double-precision floating point numbers.
int(length) Numeric field that stores integers from -2147483648
to +2147483647, but can be limited with the length
parameter. length limits the number of digits that can
be shown, not the value. Mathematical functions can
be performed on data in this field. Signifying the
unsigned parameter permits positive integers (and
zero) up to 4294967295.
integer(length) Equal to int.
longblob Equal to longtext except it is case-sensitive when
sorting and comparing.
longtext Allows storage of up to 4294967295 characters.
mediumblob Equal to mediumtext field except it is case-sensitive
when sorting and comparing.
mediumint(length) Numeric field that stores integers from -8388608 to
8388607. (Adding the unsigned parameter allows
storage of 0 to 16777215.) length limits the number
of digits to be displayed.
mediumtext Allows storage of up to 16777215 characters.
numeric(length,dec) Equal to decimal field.
real(length,dec) Equal to double field.
set(“option1”, “option2”, ...) Similar to enum field, but with set there can be none
or more than one of the available options. Set allows
up to 64 options.
Table continued on following page
749
MySQL Data Types
MySQL Field Type Description
smallint(length) Numeric field that stores integers from -32768 to
32767. (Adding the unsigned parameter allows
storage of 0 to 65535.) The length parameter limits
the number of characters to be displayed.
text Any character can be in this field, and the maximum
size of the data is 64K (65535 characters).
time Stores time as hh:mm:ss.
timestamp Stores date and time as yyyy-mm-dd hh:mm:ss. Useful
for automatically capturing current date and time.
tinyblob Equal to tinytext field, except it is case-sensitive
when sorting and comparing.
tinyint(length) Numeric field that stores integers from -128 to 127.
(Adding the unsigned parameter allows storage of 0
to 255.) The length parameter limits the number of
characters to be shown.
tinytext Allows storage of up to 255 characters.
varchar(length) Any character can be in this field, and the data can
vary from 0 to 255 characters. Maximum length of
field is denoted with the length parameter. Adding
the BINARY attribute causes comparisons and sorting
results to be case-sensitive.
year(length) Stores a year in 4-character format (by default). In
this format, values from 1901 to 2155, and 0000 are
acceptable. It is possible to specify a 2-year format
by signifying so with the length parameter. In this
format, the values from 70 to 69 are acceptable
(1970-2069).
750
Appendix D
E
MySQL Quick Reference
This appendix lists some quick reference notes for your use. These topics are covered in more
depth in Chapter 3 and on the MySQLWeb site at www.mysql.com.
Database Manipulation Commands
Use the following commands to create and make changes to your database and tables.
Command What It Does
CREATE databasename Creates the database.
CREATE tablename (field1, field2, Creates a new table.
field3, and so on PRIMARY KEY(field))
ALTER TABLE tablename WHERE condition Modifies a table in the database.
RENAME TABLE oldtablename TO Renames a table in the database.
newtablename
INSERT INTO tablename (field1, Inserts information into the table.
field2, . . .) VALUES (“value1”,
“value2” . . .)
UPDATE tablename SET field1=value1, Changes information already stored in
field2=value2 . . . WHERE condition the table.
DELETE FROM tablename WHERE condition Deletes a record from the specified
table.
DROP tablename Deletes the table.
DROP database Deletes the database.
LOAD DATA INFILE “filename” INTO Loads a large quantity of data into the
TABLE tablename database.
Connecting to the Database
Before you can connect to the database, you need four things:
❑ Database name
❑ Host Server name
❑ Username
❑ Password
Connect to the database using the following command (in PHP):
$connection = mysql_connect(“servername”, “username”, “password”);
You then need to select the appropriate database by using the following command (in PHP):

Accessing the Database
MySQL commands are inserted within your PHP code to access the database in this way:
//your information has now been updated
Retrieving Data from the Database
You can access the data stored in your tables with the following statement (you can use * to retrieve all
fields):
SELECT field1, field2 FROM tablename
Condition Clauses
Use the following conditions in conjunction with this statement:
SELECT * FROM tablename WHERE
Conditions (use % for wildcard):
field = value
field > value
field < value field >= value
752
Appendix E
field <= value field != value (field is not equal to value) field <> value (field is not equal to value)
field BETWEEN value1 AND value2
field NOT BETWEEN value1 AND value2
field LIKE value
field NOT LIKE value
field IS NULL
field IS NOT NULL
field IN (value1, value2, value3, etc)
field NOT IN (value1, value2, value3, etc)
Selecting from Multiple Tables
You can retrieve information from two or more tables at once by using the following statements:
SELECT table1.field, table2.field FROM table1, table2 WHERE
table1.field = table2.field;
or
SELECT table1field, table2field FROM table1 LEFT JOIN table2 ON
table1.table1field=table2.table2field;
Sorting the Results
You can sort the results of the SELECT query by using the following clause at the end of the statement
(and the optional ascending or descending qualifier):
SELECT * FROM tablename WHERE field1=value1 ORDER BY field2 ASC|DESC
Limiting the Results
If you would like to limit the results returned from your query, you can modify your SELECT statement
like this:
SELECT * FROM tablename WHERE field1=value1
ORDER BY field2 ASC
LIMIT offset, number_of_rows_to_be_returned
753
MySQL Quick Reference

F
Comparison of Text Editors
Many software programs are available that you can use to enter all your code. Some have better
options than others, so we’ve put together a chart to help you compare apples with apples. The
following chart lists some of the more popular editors alphabetically and compares common text
editor features, such as syntax highlighting.
Many of these editors provide similar features, so your decision really depends on your budget,
your needs, and how comfortable you are with each user interface.
You can read more about features not listed here, because many of these editors provide other
unique benefits. We encourage you to visit the following Web sites to download these programs
and get more information:
❑ AnyEdit: www.anyedit.org
❑ Dreamweaver MX 2004: www.macromedia.com
❑ EditPlus: www.editplus.com
❑ HTML-Kit: www.chami.com/html-kit/
❑ jEdit: www.jedit.org
❑ Notepad: www.microsoft.com
❑ PhpED: www.nusphere.com
❑ PHPEdit: www.phpedit.net
❑ TextPad: www.textpad.com
❑ UltraEdit-32: www.ultraedit.com
❑ WordPad: www.microsoft.com
Built-in Block
Highlighted Spell FTP Mode Line Word
Editor Syntax Checker Access Editing Numbers Wrap
AnyEdit ✓ ✓ ✓ ✓
Dreamweaver ✓ ✓ ✓ ✓ ✓ ✓
MX 2004
EditPlus ✓ ✓ ✓ ✓ ✓
HTML-Kit ✓ ✓ ✓ ✓ ✓
jEdit ✓ ✓ ✓ ✓ ✓
Notepad ✓
PhpED ✓ ✓ ✓ ✓ ✓ ✓
PHPEdit ✓ ✓ ✓ ✓
TextPad ✓ ✓ ✓ ✓
UltraEdit-32 ✓ ✓ ✓ ✓ ✓ ✓
WordPad ✓
756
Appendix F
PHP WYSIWYG
Code Web Multiple Search
Auto- Design Database Content Undo/ and
Completion Editor Connectivity Preview Redo Replace Price
✓ ✓ ✓ Free
✓ ✓ ✓ ✓ ✓ ✓ $399
✓ ✓ ✓ $30
✓ ✓ ✓ ✓ $55
✓ ✓ Free
✓ Free
✓ ✓ ✓ ✓ ✓ $299
✓ ✓ $90
✓ ✓ $29
✓ ✓ ✓ ✓ $35
✓ Free
757
Comparison of Text Editors

G
Choosing a Third-Party Host
Many people like to run their own servers out of their homes or offices, and that is a feasible solution
for hosting, if you have the time. But hosting your own Web site can lead to more problems
than it’s worth. You need to think about backup power, keeping the security holes patched, regular
maintenance, regular upgrades, and many other issues. And keep in mind that not only do you
need to have a Web server running, but you also need to have something to take care of your
domain name servers (DNS servers).
With third-party hosting solutions, you have trained IT professionals who make sure your Web
server stays up and running 24 hours a day. It’s their job to make sure your site is secure and
always available for viewing.
Hosting Options
Should you decide to have a third party host your site, you have many options to choose from
when making your hosting choice. Here are a few criteria to look at when you select a host:
❑ Supported languages: PHP, JAVA, CGI, ASP
❑ Supported databases: MySQL, PostgreSQL, MSSQL
❑ Server control: Super User (root) access
❑ Server access: Such as FTP, telnet, SSH
❑ Configuration ability: Web server settings/configurations, cron jobs, htaccess
❑ Administration GUIs: E-mail, database, user setup
❑ Bandwidth usage: Web site, e-mail, streaming media, database connections
❑ Price: Based on features, contract time, and other criteria
Keep in mind that you aren’t likely to have every combination and possibility with every host, so it’s
important that you know enough about hosts to make a well-thought-out decision before jumping
into a long contract. To that end, let’s get into a little more detail about each of those topics.
Supported Languages
First of all, we will talk about the supported languages. Obviously, because you bought this book, we’re
assuming you are looking into using PHP, but there are other languages you may need to use. There
may be a time when another language, such as Java, is better suited for a job than PHP. For example, if
you want live streaming audio or video on your site, you are likely to use a Java applet of some sort
because PHP needs a request from the server to process information. PHP can do it with different calls to
the server, but because it is more of a client request from the browser, a client-side language works much
better for this task.
There may also be times when you need to use another programming language to accomplish something a
client already has set up at a different host or server. If so, it is nice to at least have the option of using,
say, a Perl script, rather than spending the time and money to redevelop the application in PHP.
Supported Databases
Again, because this book is geared toward MySQL, you will probably need a host that supports MySQL.
However, you can use many other databases with PHP.
Here are just some of the databases that PHP can work with:
❑ MySQL
❑ PostgreSQL
❑ MS SQL Server
❑ MS Access
❑ Sybase
Depending on your situation, you may want to choose a host that has more than one of these databases
set up by default. Some larger companies, for example, are using MS SQL as their database, usually
because they are using ASP (Active Server Pages from Microsoft) for their programming. Should you
need to convert any site to PHP, you will be glad to know that PHP can connect and work nicely with
MS SQL as well. Also, keep in mind that you don’t have to continue using the other databases; you can
always port the data over to MySQL using PHP to ease the troubles of manual conversion.
Server Control and Access
Many hosts won’t give a Web developer full access or control over their hosted domain. We tend to shy
away from those hosts because you are more likely to run into problems with them when you want to
do some custom configuration to the server.
Look into the type of access your host provides. Obviously, your host will give you FTP access so you
can upload your files to the Web server. Some hosts, however, will give you FTP access, but nothing else.
The problem is that you are likely to run into a situation in which you want to configure your server. For
this you will need either telnet or SSH access to use the command line.
In fact, the ability to configure is often necessary when performing tasks that usually aren’t allowed by
hosts by default. For example, consider htaccess. With htaccess, you can deny and allow access to certain
files and directories based on the users you allow in the htpasswd file. (See Chapter 12 for more information
on htaccess.)
760
Appendix G
Along with htaccess, most hosts allow you to use cron jobs, but are not likely to set them up for you.
Therefore, you need to telnet into the server and edit the crontab file to enable you to run scheduled
tasks. There are countless configuration settings that you might want to change if your host allows you
to configure them. Keep that in mind when choosing your hosting solution.
Administration GUIs
Certain hosts offer Administration GUIs or User Control Panels as a feature of their packages. A lot of
people don’t really care for GUIs, but when you don’t have a choice, either because you don’t have sufficient
access to the server or you don’t fully understand how to get things done through telnet, a pointand-
click solution is a wonderful tool.
The interface can be as simple as one that allows you to view information about the server, or it can be
as complex as one that allows you to install applications and programming languages with the click of a
button. Also, keep in mind that many control panels have utilities that allow clients to administer their
own e-mail users themselves. With such a feature, rather than having to call you or the hosting company
to set up an e-mail account, the client can simply log on to the control panel and set up and delete users
as the need arises.
Bandwidth and Site Usage
Bandwidth and site usage factor into the overall price of hosting. Hosting companies usually give out
only so much bandwidth usage per site per month. If you go over that amount, there is usually a hefty
charge.
Consider the following issues when looking into bandwidth:
❑ Web site traffic
❑ E-mail usage
❑ Database connections
❑ Streaming media
If you have heavy activity in any or all of these areas, before you know it, you might get billed for bandwidth
overusage. You need to consider how many people will visit your site on average. In addition,
some hosts count e-mail usage in the end-of-the-month calculation used to tally your bill. Some hosts
will even go so far as to monitor your FTP access and count that toward the total bandwidth used.
Database connections don’t really relate to bandwidth usage, but hosts often limit the amount of database
connections you can make as another way to control the number of people allowed to visit the site at one
time.
Finally, streaming media is very heavy on bandwidth; should you plan to use it as a form of conveying
information to the end users of your site, your hosting bill could rise dramatically.
Pricing
You need to consider all the areas discussed so far when figuring out how much your host is worth to
you. Rather than total price, look at the price per feature. You won’t often get all the features you want
for your site, but as long as you get most of them and you choose the host that has the lowest price per
feature, you will probably make a wise hosting choice.
761
Choosing a Third-Party Host
When using price to make your choice, ask yourself how much a particular feature is worth to you.
Remember that some hosting companies require that you sign up for a full year and they won’t offer a
refund of any sort if you receive poor service or decide the service isn’t worth the money you are paying.
You want to find a host that will allow you to choose either monthly, quarterly, or yearly hosting options.
That way you don’t have to wait a full year to leave if you’re dissatisfied. Just keep in mind that when
you choose a shorter option, such as monthly or quarterly, the host will often charge a little more than if
you pay up front, or they may charge service setup fees that might be waived if you pay up front.
Making the Choice
When making your hosting decision, it’s very important to consider the criteria outlined in this appendix.
You really don’t want to get stuck in a situation in which you are unhappy with the service you are
receiving or, worse yet, your paying client is disappointed with services you recommended.
The following is a list of 10 hosting options that we feel are the best bang for your buck. You may want
to consider them when making your decision:
❑ www.olm.net
❑ www.lunarpages.com
❑ www.jumpline.com
❑ www.startlogic.com
❑ www.ipowerweb.com
❑ www.midphase.com
❑ www.infinology.com
❑ www.powweb.com
❑ www.interland.com
❑ www.websitesource.com
762
Appendix G
H
An Introduction to PEAR
PHP is a terrific scripting language. It is relatively easy to learn, especially if you already know
other programming languages such as JavaScript, C++, or Perl. In no time at all, you can get some
excellent pages up and running on your server, accessing databases, authenticating users, and providing
dynamic, up-to-date content for your visitors.
So, you just spent six months creating your company’s Web site. It’s nearly perfect—users are
being served up-to-the-minute content, and you have set up a complex Content Management
System that enables almost anyone in the company to create new content. It’s efficient, it’s pretty,
and you feel pretty darned good about it.
As you sit here thumbing through the appendixes, wondering if there are any more useful nuggets
of information, in walks your boss, the IT Manager. She tells you once again what a fine job you did,
congrats on the promotion—you know, the usual. As she gets up to leave, she stops in the doorway
and casually mentions something that is going to completely overload your work schedule:
“Oh, by the way, HR is switching to an Oracle-based database accounting package. It’s pretty slick.
And we decided that since we’ll be using Oracle anyway, all of our databases will be switched to
Oracle. That won’t be a problem, will it?”
Of course, the problem here stems from the way PHP accesses databases. The wonderful thing
about PHP is that it supports a very wide variety of databases. The bad thing is that it has
database-specific commands for each one.
Every developer has had this happen, so you are not alone. It might not be too difficult to change
your code, but it will probably be time consuming, especially if you have hundreds of pages to
update.
For example, here’s how you would run a database query with various databases:
❑ MySQL: mysql_query(“SELECT * FROM table”)
❑ Microsoft SQL: mssql_query(“SELECT * FROM table”)
❑ FrontBase: fbsql_query(“SELECT * FROM table”)
❑ Sybase: sybase_query(“SELECT * FROM table”)
❑ PostgreSQL: pgsql_query(“SELECT * FROM table”)
Those may seem fairly simple to change, but this is just scratching the surface. Oracle doesn’t even have
a _query() function. You have to use ora_parse() on the SQL statement, and then run ora_exec().
You must also consider that there may be some specific functions you are using in MySQL that have no
equivalent in Oracle. Perhaps you are even using very specific SQL statements in MySQL that are not
supported in Oracle or are executed in a different way.
Now you can see how you might have your work cut out for you. Go ahead and give your IT Manager a
resounding thump on the head for not foreseeing this change six months ago. (It’s okay; just tell her we
told you to do it.)
Wouldn’t it be cool if there were a way to write your code more abstractly, so that when you run a function
such as get_query_results(), it would be smart enough to know what type of database you are
connecting to and perform all of the necessary steps to retrieve the data? Enter PEAR.
What Is PEAR?
PEAR stands for PHP Extension and Application Repository. It is an extensive online collection of free
PHP modules and classes for many different functions. Modules exist for XML parsing, database processing,
user authentication, and more. In most cases, these modules make life easier for the developer
by hiding the details of more complex functions and by providing a friendly programming interface and
function set for accessing low-level functions. This is called abstraction, and the interface module is
referred to as the abstraction layer.
This appendix does not provide you with installation instructions or step-by-step instructions on how
to use any specific modules. Rather, our intention is to tell you about some of the more popular PEAR
modules and explain what some of their benefits and pitfalls may be. We will include simple examples
for clarification of some points, but they are not intended to be used as-is.
If you would like more information about PEAR and the modules available, visit
http://pear.php.net.
Requirements
PEAR is designed to be used with PHP versions 4.0.4 or newer, although certain extensions may have
stricter PHP version requirements. It is bundled with PHP, and the newest versions of PHP install PEAR
by default. There is a very good chance that PEAR is already installed on your server, and you can begin
using it right away.
For detailed installation instructions, visit http://pear.php.net.
The Packages
Many, many modules are available for PEAR. They are referred to as packages, and you can find them at
http://pear.php.net/packages.php. Packages are written by PHP developers using specific coding
764
Appendix H
standards. Each package is developed by a team or individual and must contain specific information
such as documentation and a list of dependencies (both to and from other packages).
The packages are defined as nodes on a tree. For example, the XML_Parser node is grouped with other
XML packages. This grouping is for organizational purposes only—dependencies have nothing to do
with the locations of nodes on a tree. The Mail package, for example, depends on the Net_SMTP package,
even though they are not connected nodes.
PEAR package developers are required to follow a strict set of coding standards called, logically enough,
the PEAR Coding Standards. One of the great things about PEAR (and open source development in general)
is that anyone can develop a package and have it inserted into the package tree. (“PEAR tree”—
isn’t that clever? We’re just waiting for the first person to create a Partridge package.)
The big package discussed in this appendix is the database package PEAR DB. Although there are many
excellent packages, this one is probably the most widely used. Many love it, and many hate it. It definitely
has its benefits, but it has a few downsides, too. We’ll touch on those shortly.
We’ll also take a look at a few other package nodes, including Authentication, Mail, Payment, XML, and
HTML.
PEAR DB
Before you delve into PEAR, you must be aware that most PEAR packages use objects and classes. If you
are not familiar with PHP’s implementation of Object Oriented Programming, you may want to read the
Classes and Objects section of the PHP manual (www.php.net/oop5). PEAR DB is designed to work
with PHP version 4.2.0 or greater.
To use PEAR DB (also written as PEAR::DB), you must include the file db.php in your page. This is your
“window” to the PEAR DB classes, and it is the only file you need to include. It will implement a class
called DB_common, which is contained in the DB/common.php file.
In common.php, you find the code that is common across different databases and some basic utility functions.
If necessary, some of the classes will be overwritten, depending on the specific database driver file
you load.
This brings us to the third file: driver. This file is loaded dynamically, depending on which database
you specify as the one you will use. If you are using MySQL, for example, DB/mysql.php is loaded. It
implements a class called DB_mysql that extends DB_common, and contains classes and functions specific
to the needs of MySQL databases.
What does all this mean? Basically, it’s mostly transparent to you as far as database access goes. You
include db.php in your page and specify the database you are accessing (along with user, password,
host, and database, as usual), and PEAR DB does the rest.
Suppose you have a database with the following two tables. You may remember these tables from
Chapter 10. Let’s use these tables in an example to see how PEAR DB compares to standard database
functions. All of the examples will use these two tables.
765
An Introduction to PEAR
id league_id alias real_name
1 2 Average Man Bill Smith
2 2 The Flea Tom Jacobs
3 1 Albino Dude George White
4 3 Amazing Woman Mary Jones
id league
1 Amazing People
2 Dynamic Dudes
3 Stupendous Seven
4 Justice Network
The first example uses MySQL-specific commands to retrieve all of the records and display them on the
screen. For simplicity’s sake, we will include the database constants in the same code. Just remember
that the best coding practice is to put them into a separate config.php file and include them.
”;
}
?>
Here is what the code looks like if you use PEAR DB:
getMessage() . “\n”);
}
$sql = “SELECT * FROM superhero s, league l WHERE l.id = s.league_id”;
$result = $conn->query($sql);
if (DB::isError($result) {
die (“Query ($sql) failed: “ . $result->getMessage() . “\n”);
}
while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) {
echo $row[‘alias’] . “ (“ . $row[‘real_name’] . “) is a member of “;
echo “the “ . $row[‘league’] . “ League.
”;
}
?>
If you load either page in your browser, you will see the following on the screen:
Average Man (Bill Smith) is a member of the Dynamic Dudes League.
The Flea (Tom Jacobs) is a member of the Dynamic Dudes League.
Albino Dude (George White) is a member of the Amazing People League.
Amazing Woman (Mary Jones) is a member of the Stupendous Seven League.
The PEAR DB method takes more lines, and the syntax is a little different (which can be especially difficult
if you are not familiar with objects). So why should you bother to use PEAR DB?
Remember that PEAR DB acts as an abstraction layer to help you interface with your database. If you
look closely at the PEAR DB code, you’ll notice that none of the functions refer to the type of database
you are accessing. In fact, they are quite generic. In contrast, the first code snippet uses mysql_ functions
throughout the code. That’s not a problem, as long as you always use MySQL.
Remember your IT Manager’s passing comment? Your company has just decided to switch from MySQL
to Oracle. Which one of these small code segments would you prefer to modify? Okay, perhaps even the
MySQL code would take only a couple of minutes, but try to imagine this on a grand scale. Also remember
that Oracle commands are different—you must pass the SQL statement to the server and commit it.
MySQL doesn’t work that way.
Now you should see the benefits of using PEAR DB’s abstraction layer. In fact, by keeping the $db_type
variable (or an SQL_DB_TYPE) constant in an included file, all you should have to do to make your entire
Web site work with the new database is change the $db_type variable from mysql to oci8—theoretically,
of course. This assumes that every SQL statement you used is compatible with both MySQL and
Oracle (which is doubtful) and that every PEAR DB function you used for MySQL is compatible with
Oracle (also doubtful). But at least you will have a lot less work to do.
There are definite benefits to using PEAR DB. For example:
767
An Introduction to PEAR
❑ It enables you to easily change your code to work with any database backend supported by
PEAR.
❑ It provides built-in error checking and error handling.
❑ It creates defaults for common methods (such as fetchRow()).
❑ It offers extended functionality—PEAR DB offers database functions that PHP does not provide
natively. For example, a method (DB::isManip) tells you whether or not a SQL statement
manipulates data or simply retrieves it. PHP has no equivalent function.
There are caveats to using PEAR DB as well:
❑ You must use SQL compatible with other databases or change your SQL statements when you
change DB servers. You would have to do that without PEAR DB, of course, but you should
know that PEAR DB does not solve this problem.
❑ PEAR DB is not as efficient as native PHP code, because you are running things in an abstraction
layer, and there may be some very complicated things going on “under the hood.”
❑ Not all database-specific functions are available through PEAR DB. For example, MySQL’s function
mysql_fetch_object has no PEAR DB equivalent. Workarounds exist for some functions
(such as casting the results of a fetchRow to an object); of course, that defeats the purpose of
having an abstraction layer.
So, should you install PEAR and use PEAR DB? Perhaps you should. You need to weigh the benefits
against potential problems and determine if it’s right for you. In the meantime, if you are working on a
big PHP project, make sure you are absolutely sure what database you will be accessing. You can avoid
a lot of headaches in the future (your IT Manager will thank you for that).
Other PEAR Packages
Pear::DB may be the most popular package available, but it is not the only package available. Let’s take
a look at a few of the other packages available in PEAR, including HTML, Authentication, Payment,
and Mail.
For more information on PEAR DB and other PEAR packages, visit http://pear.php.net.
HTML
The HTML node contains quite a few packages, designed to make some HTML functions easier. A good
example of this is HTML_BBCodeParser. This neat piece of code takes UBB style tags ([b], [img], and
so on) and converts them to HTML (, , and so on). If you have ever been to a forum online
(such as www.phpbuilder.com/board), you have seen these tags in action. This package allows you to
create your own custom BBCode, and it claims to generate valid XHTML 1.0 code.
Other HTML packages include:
❑ HTML_Menu, which enables the easy creation and maintenance of an HTML menu navigation
system.
768
Appendix H
❑ HTML_QuickForm, which provides methods for creating, validating, and processing HTML
forms.
❑ Pager for HTML pagination (1–10, 11–20, and so on).
Authentication
The Authentication packages attempt to make it a little easier to add user authentication to your site.
Auth offers the capability to use several different methods of storing and retrieving login data, such as
databases supported by PEAR, SMTP mail servers, and SAMBA, to name just a few. Auth_PrefManager
offers a method of storing and retrieving user preference data, to be used any way you see fit.
Payment
How cool would it be to be able to link your site up to several different online payment and credit card
processing companies? Now you can. These packages provide a means to connect to these systems:
❑ CyberCash online payment API.
❑ CyberMut, which allows you to use the CyberMut Payment system of the Credit Mutuel
(French bank).
❑ Payment_Clieop creates a clieop3 file for sending to a Dutch bank. We can’t tell you how
many times we have needed this!
❑ Payment_DTA creates German data transaction files.
❑ SPPLUS allows you to use the SPPLUS payment system with the Caisse d’Epargne (French
bank).
❑ TCLink connects with credit card processing through the Trust Commerce gateway.
Very international, wouldn’t you say?
Mail
The PEAR::Mail package provides functions for sending mail with PHP. It supports the PHP mail()
function, SMTP, and sendmail. It also provides e-mail address validation conforming to RFC 822
standards.
Other Mail packages include mailparse, which provides functions for parsing a mail message; Mail_Mime,
which handles the creation and manipulation of mime e-mails; and Mail_Queue, which puts large groups
of e-mails in a queue to be sent later (great for very large mailing lists).
769
An Introduction to PEAR

I
AMP Installation
This appendix guides you through installation of Apache, MySQL, and PHP for both Windows
and Linux operating systems.
Installing with Windows
By following our step-by-step guide, you will successfully have all three components installed
on your Windows system. This guide includes instructions for Windows NT, Windows 2000,
Windows XP, and Windows Server 2003.
Install Apache
Apache will act as the server for your PHP/MySQLWeb site. Installation is easy, as you will see.
This installation is for Windows NT, Windows 2000, Windows XP, and Windows Server 2003. You
can find complete installation instructions for other versions of Windows at www.apache.org.
Note that you must have TCP/IP running on your machine in order for your installation to be
operational.
The following are the basic steps for installation:
1. Go to www.apache.org, and click the HTTP Server link.
Although the Apache Software Foundation provides many different software packages,
this is the only one we are concerned with at this time.
2. Click “Download from a Mirror” to choose an FTP site for downloading.
3. Click the Win 32 Binary (MSI Installer) link to download.
If you experience problems downloading this file, you can try a different mirror site; click
the drop-down box near the top of the screen to locate one.
4. Click the MSI file to initiate the installation wizard for the Apache software.
After accepting the installation agreement, you will see a screen that is equivalent to a readme
.txt file—it gives basic information about the Apache software and where to go to find more
information. We highly recommend that you read this file.
5. Click Next. You will see the Server Information screen.
6. Enter the following information:
❑ Domain name: For example, domainname.com
❑ Server name: For example, server.domainname.com
❑ Net administrator’s e-mail address
❑ Who Are We Installing Apache For?
7. Because you are using Windows, you should install with the recommended option, “All Users.”
8. Click Next to select a setup type.
Typical installation is recommended for beginners and will suffice for most needs. Advanced
users may feel more comfortable choosing Custom setup.
9. Click Next.
The Destination Folder screen appears.
10. If you do not want your Apache files saved in the default path, click Change and select an alternate
path; then click Next.
The Ready to Install the Program screen appears.
11. Click Install to finish installation.
For configuration options and customization, please refer to Chapter 1 of this book.
Install PHP
This installation is for the PHP module on Windows 98, ME, and Windows 2000/XP/NT/2003. For all
other Windows versions, please refer to the source Web site, www.php.net. Although there is an automatic
PHP installer available at www.php.net, we strongly recommend that you use the manual installation.
At time of publication, this installer is not complete, secure, or intended for use on live servers.
The following are the steps for installing PHP:
1. Go to the PHPWeb site at www.php.net.
2. Scroll down to the Windows Binary section. If you are running your PHP on an Apache server,
as we do in this book, click the PHP Zip Package link to be able to run PHP on Apache Server.
3. Click any FTP site to begin the download.
4. Unzip your file using any standard unzip program and save it to the directory of your choice.
We recommend creating a directory named c:\php and unzipping it to this directory.
5. Before you can run PHP, you will need to rename php.ini-dist to php.ini. Make sure to
save your new php.ini file to your c:\windows (or c:\winnt) directory so Apache can
find it.
772
Appendix I
By default, the PHP installation provides two copies of your common configuration file:
php.ini-dist and php.ini-recommended. The php.ini-dist file is meant to be used for
development purposes, whereas php.ini-recommended should be used when your site goes
live, because it has additional security measures in place that the php.ini-dist does not have.
Depending on your reason for using PHP, you would choose the php.ini file that best suits
your needs. For the purposes of this book, we are going to be using the php.ini-dist file simply
because it is easier to work with and will present you with fewer obstacles. Once you are
more familiar with PHP in general, we encourage you to switch to the php.ini-recommended
file as your default. Therefore, you need to rename the configuration file as indicated in this step
in order for your PHP installation to be complete.
6. Copy php5ts.dll into the c:\windows\system32 or the c:\winnt\system32 directory so
that Apache can find it.
This file can be found in the c:\php directory, not the c:\php\dlls directory.
You now need to configure your PHP to run with Apache and MySQL. Please refer to Chapter 1 for
more information on this step.
Install MySQL
MySQL is the database that holds all the data to be accessed by your Web site. This MySQL installation
guide is for Windows 95, 98, 2000, NT, XP, and Server 2003. For all other versions of Windows, please
refer to the source Web site at www.mysql.com.
Proceed with the following steps to install MySQL:
1. Go to the source Web site, www.mysql.com, and click “Developer Zone” then “downloads” on
the navigation bar near the top of the page.
2. Scroll down to the latest stable version of MySQL, and click that link. It will be under the heading
“MySQL database server & standard clients.”
3. Scroll down to the Windows section of the downloadable files, and click Pick a Mirror.
4. Find a mirror and click to download (you can choose either HTTP or FTP to download).
5. Unzip the file to a temporary directory of your choice.
6. Click setup.exe to run the installation program. You will see the first of the Installation Wizard
screens.
7. Click Next to display the informational screen.
We highly recommend that you read this screen before you continue.
8. Click Next, which brings you to the Choose Destination Location screen.
9. If the default directory is acceptable, simply click Next; otherwise, click Browse and select a different
destination.
10. Click Next.
11. The next screen allows you to customize your installation; typical installation is sufficient for
most users.
773
AMP Installation
12. Click the setup type you prefer, and click Next to begin the installation.
After installing the appropriate files, the final screen will simply indicate the installation is complete.
Click Finish to end the wizard.
You now need to configure your MySQL installation to fit your needs. See Chapter 1 for more information.
Installing with Linux
This section covers the installation of the three components of the AMP module using a Linux system.
In this instance, we will cover an installation from the source for all three AMP components. Other
methods are available, such as RPM, deb, and ebuild. We’ve chosen to cover source installations instead
because this method offers the most flexibility and works on nearly all UNIX-like systems.
Install MySQL
The following are the steps to install MySQL for a Linux system:
1. Go to the MySQLWeb site (www.mysql.com) and download the latest stable version of the
MySQL database server.
The link for this file is most likely located at the bottom under the heading Source Downloads.
2. Grab the tarball, named something along the lines of mysql-4.0.x.tar.gz.
3. Open a console window and change the directory (cd) to the folder where you downloaded the
tarball.
4. If there isn’t a user on the system dedicated to running the mysql daemon (typically mysql),
you’ll need to create one. To do this, in the console, enter the following commands:
> groupadd mysql
> useradd –g mysql mysql
5. Extract the tarball, and change to the directory it creates:
> tar –xzf mysql-VERSION.tar.gz
> cd mysql-VERSION
VERSION is the (sub)version of the mysql source tarball you downloaded, ‘0.20’.
6. Next, configure the source this way:
> ./configure --prefix=/usr/local/mysql
Using the --prefix switch tells the installer where to put the mysql libraries and binaries after
they’re built.
7. Compile the source:
> make
8. Install the libraries and binaries:
> make install
774
Appendix I
Note that you will need to be logged in as superuser (root) to perform this step and the following
steps in the MySQL installation.
9. If this is the first time MySQL has been installed on your machine (in other words, not an
upgrade), run this script to install the initial database/tables:
> scripts/mysql_install_db
10. Fix permissions on installed files, and copy over the default configuration file:
> chown –R root /usr/local/mysql
> chown –R mysql /usr/local/mysql/var
> chgrp –R mysql /usr/local/mysql
> cp support-files/my-medium.cnf /etc/my.cnf
Any changes you wish to make to customize MySQL should be made in this file.
11. Start the MySQL daemon:
> /usr/local/mysql/bin/mysqld_safe --user=mysql &
You’ll probably want to add the previous command to whatever facilities are available to automatically
start the daemon at boot. This varies by OS, so you’ll need to find out what works on
your system. Here is one easy way to add this that works with most systems (but may not be
the best way):
> echo ‘/usr/local/mysql/bin/mysqld_safe --user=mysql &’ >> /etc/rc.local
Install Apache
Follow these steps to install Apache:
1. Go to the Apache Web site (http://httpd.apache.org) and download the latest stable version
of the Apache 2 Web server.
2. Grab the tarball, named something along the lines of httpd-2.0.x.tar.gz.
3. Open a console window, and change the directory (cd) to the folder where you downloaded the
tarball.
4. Next, extract the tarball, and change to the directory it creates:
> tar –xzf httpd-2.0.52.tar.gz
> cd httpd-2.0.52
5. Configure the source:
> ./configure \
--prefix=/usr/local/apache2 \
--enable-so \
--enable-mods-shared=max \
--enable-modules=most
Using the --prefix switch tells the installer where to put the Apache server after it’s built. For
a complete list of configuration options, run ./configure -help.
6. Compile the source:
> make
775
AMP Installation
7. Install the server:
> make install
Note that you will need to be logged in as superuser (root) to perform this step and the following
steps in the Apache installation.
8. Start the Apache daemon:
> /usr/local/apache2/bin/apachectl start
9. Add the command to start Apache to whatever boot scripts you like, so the server starts every
time you reboot. For example:
> echo ‘/usr/local/apache2/bin/apachectl start
Install PHP
Follow these steps to install PHP:
1. Go to the PHPWeb site (www.php.net) and download the latest stable version of PHP.
2. Grab the tarball, named something along the lines of php-5.0.x.tar.gz.
3. Open a console window, and change the directory (cd) to the folder where you downloaded the
tarball.
4. Next, extract the tarball, and change to the directory it creates:
> tar –xzf php-5.0.2.tar.gz
> cd php-5.0.2
5. Configure the source:
> ./configure \
--with-apxs2=/usr/local/apache2/bin/apxs \
--with-mysql=/usr/local/mysql
Make sure you point to the correct locations for the Apache 2 apxs binary and the base of the
MySQL installation directory. There are numerous configuration options for PHP, and we would
almost need a chapter just to describe them all. For a complete list of configuration options, run
./configure -help.
6. Compile the source:
> make
7. Install PHP:
> make install
You will need to be logged in as superuser (root) to perform this step.
At this point, you should configure your php.ini file as you like, verify that the necessary directives
have been placed in Apache’s httpd.conf file, and restart Apache. Refer to Chapter 1 for details on this.
776
Appendix I
Index
Index
Numerics and Symbols
: (colon) as delimiter, 160
(angle brackets and question marks) to
denote PHP code in HTML documents, 78, 113
|| (double pipe) in place of logical operator or, 79
– – (two dashes), as boundary information in multipart
e-mail messages, 336, 337
== or === (equal signs) as “equal to” operator in if
statements, 58
=> or <= (equals sign and angle bracket), as comparison operator in WHERE clause, 100 / (forward slash), as delimiter of boundaries of regex, 625 > or < (angle brackets) as “greater than/less than” operators as comparison operators, 100 in if statements, 58 {} (curly brackets), to enclose action section in if statements, 59–60 ... (ellipses), 426 => (equal sign and angle bracket), for assigning
values to keys of arrays, 68
= (equal sign) as “equal to” operator, in WHERE
clause, 100
!= (exclamation point and equal sign), as comparison
operator in WHERE clause, 100
!== (exclamation point and equals signs) as “not
equal to AND data type mismatch7” operator in
if statements, 58
! (exclamation point) as “not equal to” operator in if
statements, 58
. (period) to concatenate statements, 78, 116
_ underscore for PHP variables, 38
$ (dollar sign) for PHP variables, 38
<% and %> (angle brackets and percent signs) to
denote PHP code in HTML documents, 78
& (ampersand)
combining variables in URLs, 42
suppressing fatal error calls, 263
&& (ampersands) in place of logical operator
and, 79
\ (backslash)
advantages in HTML, 36
as delimiter of boundaries of regex, 625
+$-value functions for incrementing or
decrementing, 79
A
A List Apart (Web site for resource), 568
access levels, 451, 616, 617
accounts, user. See user login system
action buttons or images fields (input field type
on HTML forms), 54
actions, in HTML form tag lines, 53
AddMovie.php file, 153–154
AddPerson.php file, 155
admin folder, 403
admin table, 375, 376
admin_area.php file, 405–406
Administration GUIs, considerations when hiring
third-party host, 761
administrators. See also content management system
(CMS); hosts, third-party; logs of Web site activity;
security considerations
adding to admin table, 376
approval of articles, 462
central administration interface for Movie Review
Web site project, 166
ISPs disallowing programmed creation of databases,
484
keeping track of, 375
levels and access privileges, 451, 616
logins and privileges, 402–412
PHPMyAdmin, 109–110, 163, 166–168, 484, 524
requiring authorization for Web page access, 370,
402–403
sending error messages to, 251–252, 256–260,
266–267
admin_login.php file, 404–405
admin.php file
allowing creation of multiple administrators, 454–458
bulletin board application, 609–612
checking bulletin board users’ credentials, 621–623
for creating, deleting, and renaming mailing lists,
486–488, 491–494
“Send a quick message to users” link, 504
admin_transact.php file, 489–491, 493, 494–497
advertisements, 482, 514
AGAINST keyword, 478
aliases for tables, 317
ALTER, 92, 123
altertablesmovie.php file, 123
AMP (Apache + MySQL + PHP)
described, 3
installing with Linux, 774–776
installing with Windows, 771–774
roles of components, 5–6
third-party installer programs, 8
AMP installers (Web sites for resources), 8
ampersand (&)
combining variables in URLs, 42
suppressing fatal error calls, 263
ampersands (&&) in place of logical operator and, 79
Analog (third-party software for log analysis), 647–648
AND condition, 495
angle brackets ( > or < ) as “greater than/less than” operators as comparison operators, 100 in if statements, 58 angle brackets and percent signs (<% and %> ) to
denote PHP code in HTML documents, 78
angle brackets and question marks () to
denote PHP code in HTML documents, 78, 113
announcements, 482
anonymous users, 369
AnyEdit text editor, 755, 756–757
Apache program
access and error logs, 642–644
accessing executable files, 8
adding PHP, 10–11
analyzing logs with third-party software, 646, 648, 650
changing document root, 11–13
configuring, 775
customizing, 10–13, 14–16
ErrorDocument for creating custom error messages,
251–252
features and server capabilities, 6
help, 25
installing with Linux, 775–776
installing with Windows, 771–772
PHP functions, 707–708
role as component of AMP module, 5–6
testing after installation, 9–10
testing after PHP installation, 13–14
Web site, 25, 660
Apache Web Server, debugging with, 251–260
API (Applications Programming Interface), 251
applications. See coding practices; Comic Book Fan
Web site project; Movie Review Web site project;
software
Applications Programming Interface (API), 251
arrays
adding to moviesite.php file, 70–74
associative, 466, 467
concatenating with comma separators, 297
e-mail postcard images, 339, 350–352, 353
explode() function, 159–160
foreach() commands, 69–70, 102–104, 177
getting with mysql_fetch_array(), 93, 102,
103, 303
keys, 67, 68
moving pointer to next value with next(), 78
multidimensional, 68, 317, 318
normal, not zero-based, 456
overview, 67
PHP functions, 708–712
returning current value of pointer with pos(), 78
sorting, 69
syntax, 67–69
table IDs as keys, 303
testing for, 247
778
administrators
user-inputted dates, 249
values, setting, 706
viewing contents, 659
while statements, 74–77
arsort() function, 69
AS alias parameter, 99
asort() function, 69
ASP supported by third-party hosts, 759
associative arrays, 466, 467
atomicity of cells, 279
$attr variable, 202
auth_admin.inc.php file, 403
Authentication packages of PEAR, 769
auth.inc.php file, 371, 372, 374
authorization files, 371
“Authorization Required” (401) error handling, 253
auth_user.inc.php file, 383
auto_increment, 296, 525
autoincrementing fields (MySQL), 90, 169, 296, 525
avatars, 638
AWStats (third-party software for log analysis), 649
B
back references, 627
backslash (\)
advantages in HTML, 36
as delimiter of boundaries of regex, 625
“Bad Request” (400) error handling, 253
bandwidth, considerations when hiring third-party
host, 761
bbcode(), 626–627
BBcodes, 568
BBS (bulletin board system) for Comic Book Fans
admin screen, 568
admin transaction pages creation, 593–596
administrator’s user administration page, 617
administrator’s user management page, 608–616
BBcode administration, 624–628
board administration, 622–623
board settings, 618–622
breadcrumbs and navigation, 590–592
connection information file, 569
downloadable code, 574
features, 568–569
forum administration, 623
home page, 605–606, 607–608
initial login page, 605–608
pagination, 568, 586–590
possible enhancements, 638–639
post transaction pages, 596–598
regular expressions, 624–628
removal transaction page, 602–604
reusable script, 577–593
screen formatting, 574
search capability, 568, 576, 636–638
table creation, 570–575
testing, 628–636
user authentication, 568, 592
user transaction pages creation, 598–602
BBS (bulletin board systems), 567
BDB (BerkeleyDB) storage engine for MySQL
tables, 92
bigint(length), 88
black and white, image conversion to, 208–214
blob, 88
blurring images with imagefilter() function, 208
Boolean type data
with check boxes, 143
functions for data testing, 247–248
Boutell.com, 193
Boyce-Codd Normal Form, 283
breadcrumbs and navigation of BBS, 590–592
break;, 295, 298, 435, 506
brightness, altering images with imagefilter()
function, 208
browsers
closing and opening to clear session variables, 656
displaying text in, 703
in logs of Web site activity, 641, 651
bulletin boards, 567. See also BBS (bulletin board
system) for Comic Book Fans
buttons “action,” 305, 493
C
calculate_difference, 127
calendar functions of PHP, 712–716
camel case, 81
cannibalization of code, 340
capitalization
for SQL words, 114
with strtoupper() function, 150
with ucfirst() function, 150
with ucwords function, 133
captions, adding to images, 214–218
carriage return and new line (\r\n), 334
Cart32 shopping cart software, 519
cart.php file, 520, 534–537
case. See capitalization; case-sensitivity
779
case
Index
case-sensitivity
of array indexes, 140
of OOP classes and methods (functions), 81
of PHP variables, 38
case statements, 300
catch method in try/catch method of handling
PHP Exceptions, 269–270
cbashop.php file, 520, 527–530
ceil() function, 40, 304
cells, atomicity, 279
CGI supported by third-party hosts, 759
chapter6.mysql script, 163
charedit.php file, 308–311, 319–323
char(length), 86
charlist.php file, 306–308, 312, 316–319
char_main table, 289
char_transact.php file, 291, 305
“cheat sheet” PHP quick reference, 703–706
checkboxes (input field type on HTML forms), 53
checked attribute, 322
check_image.php file, 199, 200–201, 203–205,
220–222, 224–225
checking for, 238–239
checkout2.php file, 520, 544–551
checkout3.php file, 520, 551–559
checkout.php file, 520, 539–544
“child” and “master” pages, 121
classes in OOP, 80
classes in PHP
defining for encapsulating functionality, 358–359
functions for handling, 716–717
reusable mail class, 355–362
class.SimpleMail.php file, 355–357, 358–361,
488–489, 494
CMS (content management system). See content
management system (CMS)
cms_access_levels table, 420
cmstables.php file, 417–420
cms_users table, 421
Codd, E. F., 276
code: maintainability considerations. See also
debugging; troubleshooting
advantages of multiple scripts, 158
caution on use of ternary comparison operators, 150
of hosting Website, 759
coding practices
cannibalization, 340
guidelines for professionalism, 32, 283–284
importance to efficiency, future modification,
expansion, 32
importance to maintainability, 150, 158
importance to troubleshooting, 31, 656
reusable mail class, 355–362
reusable script, 422–425
colon (:) as delimiter, 160
color quality
image conversion to grayscale, 208–214
maintaining for images, 207
colorizing images with imagefilter() function, 208
colors, alternating backgrounds of table rows, 319
columns
distributing data evenly in, 304
sorting data by, 316, 318
combo boxes, 176–177
Comic Book Fan Web site project. See also BBS
(bulletin board system) for Comic Book Fans;
logs of Web site activity; online selling from
Comic Book Fan site
account creation, 448–454
administration page, 454–458
article creation, 458–462
article reviewing system, 462–469
article viewing pages, 469–472
Character Database home page, 312
columns in char_main table, 288–289
creating first table, 279–283
creating and modifying superhero powers, 301–303
creating tables, 286–289
displaying list of characters (charlist.php file),
306–323
downloadable code for, 291
editing characters’ features (charedit.php file),
308–311, 319–323
main index/login screen, 444–448
normalizing tables, 279–283
overview, 3, 85, 290–291
search feature, 477–478
standards (design rules) for table structure/names,
283–284, 317
transaction page processing, 291–301
user information maintenance/control panel, 472–477
comicsite (Comic Book Fan Web site project), 286
commenting
in PHP, 31
in professional caliber code, 32
comment.php file, 470, 471
commit.php file, 173, 187, 189, 233–234, 243–246,
247–250
780
case-sensitivity
comparison operators
LIKE in WHERE clause, 100
symbols in WHERE clause, 100
ternary, 150
compose.php file, 441, 458–462, 631–633
composite primary keys, 279
concatenating statements with period (.), 78, 116
conditional operators
AND, 495
Boolean type data functions for testing, 247–248
conditional statements. See also foreach(); if();
WHERE clause of SELECT statement; while()
if/else, 59–60, 434, 453, 705
ifempty(), 238–239
conditions, handling unmet, 271
config.php file
changeable values in one file, 288
holding MySQL connection info and password, 504
holding server, username, password, and database
values, 482
to include in PHP files accessing database, 287
included in header.php of bulletin board application,
622
including versus requiring, 303
requiring versus including, 484
setting up constants or variables for bulletin board
system, 584
configuring
Apache, 775
my.cnf file, 21–24
MySQL, 774–775
PHP, 776
PHP5 for MySQL, 16
confirmmail.php file, 353
confirm.php file, 344–345
conn_comic.php file, 338
connecting to servers, 93–94, 303, 316, 338
with mysql_connect(), 92, 93, 303, 316, 494
conn.inc.php file, 378, 403
conn.php file, 417, 420, 451, 475, 569
constants, in PHP, 37–38
constructors in OOP, 81
content management system (CMS)
account creation, 448–454
administration page, 454–458
advantages, 415–417, 479
article creation, 458–462
article reviewing system, 462–469
article transactions, 437–444
article viewing pages, 469–472
browser functions, 431
daily comic idea, 479
database structure creation, 417–421
definitions, 415–416
headers, 429–431
main index/login screen, 444–448
output functions, 422–424, 426–429
reusable script creation, 422–425
search feature, 477–478
transaction pages, 431–437
user information maintenance/control panel, 472–477
content of Web sites, 415–416
contrast, altering images with imagefilter()
function, 208
$_COOKIE, 50
cookies. See also users
described, 370, 399
ending or deleting, 401
“headers already sent” (PHP error message),
49, 52, 657
longevity setting, 50
passing session ID, 49
passing variables in PHP, 47, 49–53
security considerations, 49–50, 370
setting, 50–53
tracking with PHP, 399–402
cookies_set.php, 400
copyright notices
adding to images, 214–220
possible placement in footer.php file, 477
counters, 304
cpanel.php file, 472–477
CPUs, multiple, 7
CREATE, 92
CREATE DATABASE, 285–286, 339, 484
CREATE TABLE, 288–289, 575, 576, 637
CREATE TABLE IF NOT EXISTS, 285, 289, 420, 575,
576, 577
create_images_table.php file, 197
createmovie.php file, 95
create.php table, 519, 520–522
createreviews.php file, 129–130
createtemp.php file, 519, 532–534
credit card processing considerations for online
selling, 561
CSS (cascading style sheets), 429, 568
curly brackets ({}), to enclose action section in if
statements, 59–60
781
curly brackets ({})
Index
customer feedback
from access and error logs, 641–642, 651
considerations for online selling sites, 563
customer service considerations for online selling,
561, 563
custom_error.php file, 264–266
customers. See online selling from Comic Book Fan site
customers table, 522
D
dashes ( – – ), as boundary information in multipart
e-mail messages, 336, 337
data types (MySQL field types), 86–89
database creation. See also Web site creation
for Comic Book Fan Web site project, 279–283,
286–289
for Movie Review Web site project, 94–98
in MySQL, 285–286
database normalization, 278, 279–283
database system, MySQL as, 7
databases, relational. See also RDBMS (relational
database management systems); tables
caution on ISPs disallowing programmed creation of
databases, 484
accessing with config.php, 287, 288
considerations for placement of tables, 484
inserting simple records, 166–170
keys, 277
for mailing lists, 482–485
normalization, 278, 279–283
overview of structure, 276–278
PHP’s database specificity problem, 763
querying, 99–102
referential integrity, 278
relationships, 277–278
selecting with mysql_select_db(), 92, 494
specifying active, 92
supported by third-party hosts, 760
datatypes, 86–89, 284
date() function, 58–59, 87, 429
date.php file, 59
dates
checking for errors in input, 239–250
date/time/calendar functions of PHP, 58–59, 87, 429,
712–716
getting, 260
timestamp function, 249–250
datetime(), 87
DB/common.php file, 765
db_insertpics.php file, 338
db_makeconfirm.php file, 340, 350
db.php file, 765
debugging. See also code: maintainability considerations;
troubleshooting
caution on register_globals setting, 15, 41, 44,
295, 330, 353, 655–656
with Apache Web Server, 251–260
with echo, 658–659
error codes
returned by MySQL, 576
testing for specific code, 576–577
typically found during Web browsing, 253
ErrorDocument for creating custom error messages
(Apache), 251–252
MySQL query, 166–170
one language at a time, 166
with PHP Applications Programming Interface (API), 251
piecemeal execution, 659
with print_r( $_POST ), 140
queries in MySQL before insertion into code, 166,
177, 191
SQL statements in phpMyAdmin, 166–168
testing on various platforms, browsers, preferences
settings, etc., 659
value of good coding practices, 32
decimal handling, 40, 87, 304
decimal(length,dec), 87
decrementing variables automatically in PHP, 79
default: option, 300
default settings for PHP, 15–16
define() function, 37–38
DELETE, 92, 178–182, 300, 539
delete_account.php file, 389
delete.php file, 178–179
delete_user.php, 410
deleting
cookies, 401
mailing lists, 486–488, 491–494
matching rows in joined tables, 298
records, 178–183
and referential integrity considerations, 278
delivery issues for online selling, 518, 563
DESCRIBE, 92
directories
/images/, 196
admin, 403
for content management system (CMS) files, 417
PHP functions for handling, 717–720
782
customer feedback
for postcard images, 337
for thumbnails, 220
for uploaded images, 200–201
tag, 429
do/while loops, 75, 271
document root for Apache, 11–13
dollar sign ($) for PHP variables, 38
double quotation marks, caution on use of HTML
with PHP, 36
downloadable code for Comic Book Fan Web site
project (Web site for), 291
downloadable postcard images (Web site for), 337
Dreamweaver text editor, 755, 756–757
DROP, 92
drop-down boxes/select fields (input field type on
HTML forms), 53
DROP TABLE, 420
dynamic page titles, 149–150
E
e-commerce. See online selling from Comic Book
Fan site
e-mail encryption with fingerprint or hash (Web site
for), 352
e-mailing. See also mailing lists
collecting data and sending messages, 327–331
getting confirmation, 339–355
multipart messages (for plain text and HTML),
334–337
PHP setup, 325–326
reusable mail class, 355–362
sending error messages to administrators or
Webmasters, 251–252, 256–260, 266–267
sending HTML code, 331–332
sending HTML code using headers, 332–334
sending simple messages, 326–327
storing images, 337–339
uses, 325
E_ALL (PHP error type), 261, 322
echo function, 33–34, 35–36, 78, 271, 659
echoUserList(), 457
ecommerce database, 522
E_COMPILE_WARNING (PHP error type), 261
E_CORE_ERROR (PHP error type), 260
E_CORE_WARNINGS (PHP error type), 261
edge detection of images with imagefilter()
function, 208
editforum.php file, 618–619
editing
accounts, by administrator, 402–403, 412
accounts, by users, 383–385
characters’ features (charedit.php file), 308–311,
319–323
records, 183–191
script with text editors, 755, 756–757
user accounts, 385–399
values, 190
EditPlus text editor, 755, 756–757
E_ERROR (PHP error type), 260, 265, 266
ellipses, in PHP with GD, 194
ellipses (...), 426
embossing images with imagefilter() function, 208
empty() function with if() statements, 238–239
encryption with fingerprint or hash, 352
enctype form attribute, 200
E_NOTICE, 260, 263
E_NOTICE (PHP error type), 260, 263
enum(“option1”,”option2”, ...), 87, 284
=<<), as comparison
operator in WHERE clause, 100
equal signs (== or ===) as “equal to” operator in if
statements, 58
ereg() function, 249
error codes
returned by MySQL, 93, 576
testing for specific code, 576–577
typically found during Web browsing, 253
error handling in PHP. See also debugging
customized, 261–266
error types, 260–261
error_reporting() function, 263
with Exceptions, 269–270
exceptions for, 269–270
functions for, 721
“headers already sent,” 49, 52, 657
mysql_errno(), 576
parse errors, 272
reporting, displaying, logging settings for PHP, 15
unmet conditions, 271
error messages
e-mailing to administrators or Webmasters, 251–252,
256–260, 266–267
“headers already sent,” 49, 52, 657
783
error messages
Index
error messages (continued)
international, 7
“no services installed,” 9
to users, customizing with Apache ErrorDocument,
251–252
error numbers, mysql_errno(), 576
ErrorDocument, for creating custom error messages
(Apache), 251–252
error.php file, 253–254, 257–260
error_reporting() function, 263
errors in user input
adding messages to error queue, 248
checking dates and numbers, 239–250
detecting and notifying users, 238–239
displaying decoded message, 239
escaping HTML double quotes, 36
E_STRICT (PHP error type), 260, 261
ethical considerations
for mailing lists, 514–515
for online selling, 559–561
E_USER_ERROR (PHP error type), 261
E_USER_NOTICE (PHP error type), 261
E_USER_WARNING (PHP error type), 261
E_WARNING (PHP error type), 260
Exceptions for error handling in PHP, 269–270
Exceptions.php file, 270
exclamation point (!) as “not equal to” operator in if
statements, 58
exclamation point and equal sign (!=), as comparison
operator in WHERE clause, 100
execution time settings for PHP, 15
exit() function, 506
explode() function, 159
extract() function, 102
ezmlm_hash(), 727
F
fatal errors, 261
feature_error.php, 267–268
feedback from customers, considerations for online
selling sites, 563
field types, 86–89
fields
adapting to incomplete user input, 229–239
automatically incrementing by one, 90, 169, 296, 525
defining names and parameters, 96–97
described, 86
hidden, 323
on HTML forms, grouping, 452
null/not null, 89
types, 86–89
unique, 90
HTML function, 452
Fifth Normal Form, 283
file size, uploads settings for PHP, 16
file types
converting image files, 203–208
GIF files, 207, 219
image files usable with GD, 194, 201–202
JPEG files, 207, 210, 213, 214, 222, 224
PNG files, 207
WBMP (Wireless Bitmap) files, 201
filenames, checking for duplicates, 201
files. See also files by file name
including with include(), 60–62, 159, 303, 705
PHP functions for handling, 717–720
fingerprint or hash encryption, 352
First Normal Form (1NF), 283
firstmail.php file, 326
firstprog.php file, 33–36
floating-point numbers in PHP, 15
floor() function, 40
folders. See directories
fonts
error if not installed on server, 215
with HTML inside PHP, 36
specifying in imagettftext() function, 217–218
for text embedded in images, 213, 214, 217–218
footer.php file, 425, 586
for(), 706
“Forbidden” (403) error handling, 253
foreach()
applying command to every row in results set,
102–104
error trapping, 271
looping through array, 177, 295, 706
returning “invalid argument” warning, 352
syntax, 69–70, 706
foreign keys, 277, 282
foreign tables, 277
forgotpass.php file, 445, 448, 606
forgotten passwords, 444–445, 448, 606
FORM, 138–139
form1.html file, 136–138
form2.html file, 141–143
form3.php file, 145–146
form4.php file, 150–152
format errors in input. See errors in user input
784
error messages (continued)
formatting text
dates, 714–716
with HTML inside PHP, 36
formprocess1.php file, 136–137, 140
formprocess2.php file, 142–143
formprocess3.php, 146–147
formprocess3.php file, 146–147
forms (HTML)
caution on self-posting, 493
adapting to incomplete user input, 229–239
allowing user input to Movie Review Web site, 150–160
creating, 138–141
driving user input, 141–150
grouping fields, 452
limiting input choice, 141–143
overview, 53–54
passing variables, 53–57, 704
PHP receipt and processing of data, 135
with radio button and multiline list boxes, 145–148
using to obtain user information, 54–57, 135
Forms of normalization, 283
forums in bulletin board systems, 567. See also BBS
(bulletin board system) for Comic Book Fans
forum_styles.css file, 574
forward slash (/), as delimiter of boundaries of
regex, 625
Fourth Normal Form, 283
Foxserv (AMP installer), 8
“From:” header on e-mails, 496, 505
FROM parameter, 99, 102, 303
FTP server access, considerations when hiring
third-party host, 760–761
full text indexes, 421, 478, 576, 638
FULLTEXT INDEX keyword, 421
FULLTEXT KEY keyword, 421
Fulltext Keys, 421, 637
functions, PHP. See PHP functions
functions.php file, 577–583
G
gallery.php file, 222–224
GD (Graphics Draw) library
description and sources, 193
file types usable with, 194
testing, 194–195
gd_info function, 194–195
gdtest.php file, 194–195
$_GET global array, 159, 161, 177
GET method, 139, 655–656
getdate() function, 260
getimagesize() function, 201–202, 207
getprod.php file, 520, 530–532
GIF files
imagecreatefromgif() function, 207, 219
imagegif() function, 207
Gifts for Engineers (Web site for resource), 518
global $varname, 62
graphics. See also images
importance to online selling, 560
grayscale, image conversion to, 208–214
guarantees, policy considerations for online selling, 561
H
hash or fingerprint encryption, 352
hash value display in PHP, 727
header() in mail() function, 301, 330, 332–334,
336, 354, 355
header.php file
for bulletin board application, 584–586
checking for user’s access level, 592
reusable, 424–425
as standard header for all Web display pages, 475
using sessions title, login status, and appropriate
menu items, 429–431
welcome message to Movie Review Web site project, 61
headers
“From:” header on e-mails, 496, 505
raw HTTP, 149
“headers already sent” (PHP error message),
49, 52, 657
headings, defining for tables, 111–114
help sources, 25
heredoc syntax, 79, 113, 350
hidden fields, 323
hits, number of, 651
host name, MySQL server, 93
hosts, third-party
Administration GUIs or User Control Panels, 761
advantages, 759
bandwidth and site usage, 761
pricing, 761–762
server control and access, 760–761
supported databases, 760
supported languages, 760
Web sites for, 762
.htaccess files, 252, 366–370
785
.htaccess files
Index
HTML. See also forms
advantages of ob_start and ob_end_flush, 657
e-mailing, 331–334
integrating with PHP, 30, 33, 34–37
for mass e-mailings, 482
PHP functions for handling, 721–722
text conversion to readable, 429
HTML forms (Web site), 452
HTML-Kit text editor, 755, 756–757
HTML packages of PEAR, 768
HTML references (Web site), 138
htmlentities(), 627
html_entity_decode(), 627
htmlspecialchars(), 429, 452, 461, 475, 626
http://localhost/chapter6/index.php, 188
HTTP Analyze (third-party software for log analysis),
650
HTTP protocol, PHP functions for, 721–722
httpd-2.0.x.tar.gz file (tarball), 775
httpd.conf file, 252, 366
http.php file, 425, 584
hyperlinks in tables, 120–122
I
if/else statements, 59–60, 434, 453, 705
IF NOT EXISTS keyword, 285, 289, 420, 575,
576, 577
if() statements
date display exercise, 58–59
distributing data evenly in columns, 304–305
with else, 59, 705
with else in leap year example, 59–60
with (empty()), 238–239
establishing where code actions are happening, 271
nested, 705
operators used with, 57–58
special syntax considerations, 58
with try()...catch() blocks, 270
used alone, 57, 704
IGNORE keyword, 295, 297, 300
imagecopymerge() function, 219–220
imagecopyresampled() function, 207
imagecreatefromgif() function, 207, 219
imagecreatefromjpeg() function, 210, 213,
222, 224
imagecreatefrompng() function, 207
imagecreatetruecolor() function, 207
imagedestroy() function, 208
imagefilter() function, 208, 213
imagegif() function, 207
imagejpeg() function, 207, 214
ImageMagick, 201
imagepng() function, 207
images
adding caption, text, copyright notice, 214–220
adding watermarks and merging, 218–220
allowing users to convert to grayscale, 208–214
converting file types, 203–208
creating table of, 196–202
creating thumbnails, 220–225
displaying, 131–134
file types usable with GD, 194
importance to online selling, 560
importing from GD (Graphics Draw) library, 193
maintaining color quality, 207
making negatives with imagefilter() function, 208
PHP functions for handling, 722–727
storing and e-mailing, 337–339
testing for file types usable with GD, 201–202
WBMP (Wireless Bitmap) files, 201
imagettftext() function, 217–218
IN keyword, 300
.inc files, 60
include(), 60–62, 159, 303, 705
incrementing or decrementing automatically
field contents, 90, 169, 296, 525
variables, 79
indenting
in PHP, 31
in professional caliber code, 32
INDEX, 421
indexes
described, 90, 637
full text, 421, 478, 576, 638
number permitted in MySQL, 7
setting keys, primary keys, and fulltext keys, 421, 637
index.php file
ADD button click results, 174–176
for administrator registration, 403
home page for bulletin board application, 605–606
including files, retrieving articles for Comic Book
Appreciation site, 447
looking for login information, 376–377, 382
main index/login screen for Comic Book Appreciation
site, 445–446
revealing home page, 389
786
HTML
start page and environment settings for Movie Review
Web site project, 164–165
using three-table JOIN for retrieval for bulletin board
application, 607–608
INNER JOIN, 495
InnoDB storage engine for MySQL tables, 91
input time settings for PHP, 15
input type=”file”, 200
input type=”radio”, 148
input type=”submit”, 140, 142, 149
input type=”text”, 139
INSERT IGNORE, 295, 297, 298
INSERT INTO tablename VALUES, 92, 295–296, 539
installation problem troubleshooting, 653
installer programs
caution on use of automatic PHP installer, 772
third-party, 8
installing
Apache
with Linux, 775–776
with Windows, 771–772
MySQL
with Linux, 774–775
with Windows, 773–774
PHP
with Linux, 776
with Windows, 772–773
instantiating objects in OOP, 80
integers
bigint(length), 88
int(length), 86, 228, 284
int(length)unsigned, 86, 87
mediumint(length), 88
smallint(length), 87
tinyint(length), 87, 228
integers, functions using, 89
“Internal Server Error” (500) error handling, 253,
255–256
int(length), 86, 228, 284
int(length)unsigned, 86, 87
IP addresses, in logs of Web site activity, 641
IRC channels (Web site for), 660
is_array() function, 247
is_bool() function, 247
is_numeric() function, 247, 248
is_object() function, 248
ISPs, some disallowing programmed creation of
databases, 484
isset() function, 66, 429–430
is_string() function, 247
J
Java supported by third-party hosts, 760
JavaScript For Dummies, Third Edition (Wiley, 2000), 351
JavaScript for postcard image selection, 351
jEdit text editor, 755, 756–757
JOIN function, 107–108, 316
joining tables
with INNER JOIN function, 495
with JOIN function, 107–108, 316
with LEFT join function, 109
with WHERE clause of SELECT command, 320
JPEG files
imagecreatefromjpeg() function, 210, 213,
222, 224
imagejpeg function, 207, 214
junk e-mail and spam, ethical considerations, 514, 561
junk snail mail, ethical considerations, 561
K
KEY keyword, 421
keys
arrays, 67, 68
composite primary, 279
foreign, 277, 282
Fulltext, 421, 637
FULLTEXT KEY keyword, 421
indexes to tables, 90, 169
NULL as primary, 296
primary, 90, 169, 277, 279, 421
PRIMARY KEY keyword, 421
in relational databases, 277
searching tables, 90, 169
setting, 421, 637
table IDs as, 303
UNIQUE KEY keyword, 421
Web site for, 637
Web sites for information, 278, 637
keyword searches by search engines, 652
L
languages supported by third-party hosts, 760
leap year calculation, 59–60
$leapyear, 59
787
$leapyear
Index
leapyear.php file, 59
LEFT join statement, 109
HTML function, 452
LIKE comparison operator, 100
LIMIT() statement, 99, 178
line numbering
in PHP, 32, 54
in professional caliber code, 32
for troubleshooting PHP parse errors, 654
line returns
with \n\n, 337
in PHP, 31
links and linking
broken, checking error logs for, 651
to Comic Book Fan site products, 529, 562
settings for PHP, 16
tables, 117–120
Linux
installing Apache, 775–776
installing MySQL, 774–775
installing PHP, 776
localhost SMTP setting, 326
logged_admin.php file, 404
logged_user.php, 377, 382
logging updates, settings for, in MySQL, 23
logical operators
Boolean type data functions for testing, 247–248
symbols in place of or, 79
in WHERE clause, 100
login.php file, 56, 61, 64, 72, 371, 372, 446,
448, 605
logins. See also sessions; user login system
to BBS, 598–602, 605
persistent connection settings, 16, 400, 401
with PHP, 370–375
with sessions, 47, 370, 395
logos, 218–220
logs of Web site activity
advantages, 641–642
analyzing with third-party software
Analog, 647–648
AWStats, 649
HTTP Analyze, 650
Webalizer, 646–647
WebTrends, 648
Apache access and error logs, 642–644
PHP functions for handling, 721
types, 641
longblob, 88
longtext, 88
loops
with do/while, 75, 271
establishing where code actions are happening, 271
foreach() function, 69–70, 102–104, 177, 271,
295, 352, 706
with while() statement, 74–77, 102, 104, 115, 271
M
mail() function
building subject and body parameters for, 509
compared to send(), 359, 362
header() in, 301, 330, 332–334, 336, 354, 355
inserting From address, 505
returning True or False, 331
sending simple e-mail, 326–327, 436–437
syntax, 727
using with error occurrence, 260
Mail packages of PEAR, 769
mail_html.php file, 357
mailing lists. See also e-mailing
BCC field, 496
database preparation by administrator, 482–485
ethical considerations of spam and opt-in/opt-out
options, 514–515
mailing list handling by administrator, 486–497
signup form handling, 497–511
subscription removal handling, 511–513
uses, 481–482
mail_multipart.php, 358, 361–362
mail_quick.php file, 358, 362
mail_text.php, 357, 361
Mailtraq mail server, 326
maintainability considerations. See code: maintainability
considerations
make_table.php, 287–288
management of Web site systems, 416. See also
administrators
many-to-many relationship of databases (M:N), 278, 282
“master” and “child” pages, 121
MATCH keyword, 478, 638
mathematical functions in PHP, 40, 727–729
max() function, 40
md5() function, 352
mediumblob(), 88
mediumint(length), 88
mediumtext(), 88
members in OOP, 80
memory limit settings for PHP, 15
MEMORY storage engine for MySQL tables, 91
788
leapyear.php file
menus, possible placement in footer.php file, 477
merchandise, considerations for online selling, 518, 563
MERGE storage engine for MySQL tables, 91
methods
in HTML form tag lines, 53
in OOP, 80
MIME capabilities, 334
min() function, 40
mktime() function, 249–250
ml_lists table, 485
ml_subscriptions table, 485, 507, 512
ml_users table, 485, 506
modcart.php file, 520, 532, 537–539
modifyimage.php file, 210–211, 212, 213–214,
215–216, 217–220
Movie Review Web site project. See also logs of
Web site activity
adapting to incomplete user input, 229–239
adding captions/text in images, 214–218
adding items, 159–160
adding a list of favorite movies, 62–67
adding variables, 39
adding watermarks and merging images, 218–220
allowing user input from forms, 150–160
allowing users to convert images to grayscale, 208–214
allowing users to upload images, 196–202
central administration interface, 166
choosing reviews with while statement, 74–77
converting image file types, 203–208
creating new page for display of additional data,
124–128
creating thumbnails, 220–225
database/table creation, 94–98
default response, 159
defining table headings, 111–114
deleting records, 178–183
displaying images, 131–134
editing records, 183–191
getting information via forms, 54–56
hyperlinks in tables, 120–122
inserting records into database, 166–177
inserting simple record from PHPMyAdmin, 166–170
linking tables, 117–120
overview, 3, 85
passing special characters in URLs, 45–46
passing visitor username, 47–49
populating tables, 94–98, 114–120, 122–123,
129–130
sending table to browser, 116
setting cookies, 51–52
skeleton script, 159
sorting lists with arrays, 70–74
URL variables, 42–45
welcome message, 60–62
movie table, 94, 96, 98, 228
movie1.php file, 43, 44, 46, 47–48, 51, 54, 56–57,
62, 63, 64, 66, 72–73, 75
moviedata.php file, 95, 97
movie_details.php, 123, 124, 126–127, 130,
131–132
movie.php file, 170–172, 176, 184–186, 189,
229–233, 240–243
moviesite.php file, 37–38, 42, 44, 48, 51, 55, 63,
66, 70–74, 76
movietype table, 94, 97, 98, 170
MSSQL databases, supported by third-party hosts, 760
multidimensional arrays, 68, 317, 318
my.cnf file, configuring, 21–24
MyISAM storage engine for MySQL tables, 91
mysql-4.0.x.tar.gz file (tarball), 774
MySQL program
commands (quick reference), 751–753
configuring, 774–775
connecting to server, 93–94, 303, 316
data or field types, 747–750
data upload settings, 23–24
database manipulation commands, 751–753
documentation, searching and commenting upon, 109
error fixing, 166–170
execution options for CREATE DATABASE
statement, 286
features, 7
help, 25
installing with Linux, 774–775
installing with Windows, 773–774
password setup, 21
PHP interactions, functions used with, 92–93,
729–731
PHP5 configuration for, 16
query and error logs, 644–646
as relational database system, 7, 85, 86, 129, 170
role as component of AMP module, 5–6
starting, stopping, shutting down server, 17–18
structure overview, 86–92
syntax and commands, 92
TCP/IP protocols requirement, 17
testing installation, 17–19
tracking sessions with MySQL and PHP, 376–382
update log settings, 24
upper case for, 114
789
MySQL program
Index
MySQL program (continued)
user setup, 19–20
users and privileges settings, 24–25
viewing database tables, 19–20
Web site, 7, 660
mysql_connect(), 92, 93, 303, 316, 494
mysql_errno(), 576
mysql_fetch_array(), 93, 102, 103, 303
mysql_fetch_assoc(), 103, 303
mysql_fetch_error(), 93
mysql_fetch_rows(), 93, 303
mysql_insert_id(), 79, 169, 296, 506, 557
mysql_query(), 92, 97, 104, 298, 576
mysql_select_db(), 92, 494
N
\n\n new lines, 337
naming variables, 131
navigation issues
breadcrumbs in Comic Book Appreciation Bulletin
Board System (CBA board), 590–592
for online selling sites, 562
negative images with imagefilter() function, 208
negative number display, 124
nested if() statements, 705
Netcraft (Web site for resource), 6
networks, PHP functions for communicating with,
731–732
new keyword in OOP, 82
new lines

tags with nl2br(), 626
with \n\n, 337
newsletters, 482, 514
next() array function, 78
NEXT (Next Page) button, 586–590
nl2br(), 429, 626
“no services installed” Apache error message, 9
non-transaction-safe tables (NTSTs), 91
normalization of relational databases, 278, 279–283
“Not Found” (404) error handling, 253, 254–255, 651
Notepad text editor, 755, 756–757
notices (runtime), 261
notifications of Web site changes or downtime, 482
null/not null fields, 89
NULL values, 296
number_format() function, 40
numbers
bigint(length), 88
checking for errors in input, 239–250
int(length), 86, 228, 284
int(length)unsigned, 86, 87
mediumint(length), 88
smallint(length), 87
testing for numeric data, 247
tinyint(length), 87, 228
O
Object Oriented Programming (OOP), 79–82
objects
in OOP, 80
PHP functions for handling, 716–717
testing for, 248
ob_start and ob_end_flush, 657
ON parameter, 109, 316, 317, 318
one-to-many relationship of databases, 278
one-to-one relationship of databases, 278
online selling from Comic Book Fan site
advantages, 517
checkout step 1, 539–544
checkout step 2, 544–551
checkout step 3, 551–559
communication issues with customers, 563
customer feedback issues, 563–564
customer trust issues, 560–561
database population with products, 524–527
databases and tables creation, 520–523
files overview, 519–520
home page creation, 527–530
merchandise pricing and delivery, 562–563
navigation issues, 562
overview, 518, 559–560, 564
privacy issues, 561
product viewing, 530–532
professional look of site, 562
shopping cart abandonment issues, 533–534
shopping cart contents updating, 537–539
shopping cart table creation, 532–533
shopping cart viewing, 533–537
OOP (Object Oriented Programming), 79–82
Open Source Initiatives (OSI), 4
open source programs, 4–5
opt-in versus opt-out options, ethical considerations
for mailing lists, 514–515
Oracle, considerations for database format switch to,
763–764
ORDER BY parameter, 99, 102, 109, 130, 303
orderdet table, 523
ordermain table, 523
790
MySQL program (continued)
output buffers in PHP, 15, 657, 732–733
outputfunctions.php file, 422–424, 426–429, 468
outputStory(), 427–428, 468
P
“Page Not Found” (404) error handling, 253, 254–255,
651
page views, 651–652
pages
creating new and displaying data, 124–128
“master” and “child,” 121
missing, error notification of, 251–252
navigation issues
breadcrumbs in Comic Book Appreciation Bulletin
Board System (CBA board), 590–592
for online selling sites, 562
passing variables between, 40–41
popularity determination from logs of Web site activity,
641, 651–652
requiring authorization of users, 370
transaction, 291, 294–301
paginate() function, 588
pagination, in Comic Book Appreciation Bulletin Board
System (CBA board), 568, 586–590
parse error handling and troubleshooting, 272, 653–654
parsing tags (PHP), 14
password fields (input field type on HTML forms), 53
$password variable, 57
passwords
administrator’s, immediate removal from server, 420
asking for, 453
checking against database, 383–384
forgotten, 444–445, 448, 606
MySQL server, 93
requiring for access to folder, 366–367
secure passing with sessions, 47–49
pattern modifiers, 626
patterned replacements, 626–628
Payment packages of PEAR, 769
PCRE (Perl Compatible Regular Expressions), 624–628
PEAR (PHP Extension and Application Repository)
abstractions and abstraction layers, 764, 767
advantages, 764
advantages of PEAR DB, 767–768
Authentication packages, 769
description and requirements, 764
HTML packages, 768
Mail packages, 769
packages (modules) as nodes on trees, 764–765
Payment packages, 769
PEAR DB package, 765–768
Web site, 764
pending.php file, 462–463, 465, 466–467
people table, 94, 97, 98, 177
period (.) to concatenate statements, 78, 116
persistent connection settings, 16, 400, 401
photo journal project, 479
php-5.0.x.tar.gz file (tarball), 776
PHP error handling
customized, 261–266
error logs, 644
error page, creating, 267–269
error types, 260–261
with Exceptions, 269–270
finding syntax errors, 271
parse errors, 272, 653–654
unmet conditions, 271
.php extension, 30
PHP functions
Apache server, 707–708
arrays, 708–712
class/object/function handling, 716–717
configuration information, 733–735
date/time/calendar, 712–716
directories, files, 717–720
error handling, 721
HTTP protocol, 721–722
images, 722–727
mail, 727
mathematical, 40, 727–729
miscellaneous, 745–746
MySQL interactions, 92–93, 729–731
network communications, 731–732
output buffers, 15, 657, 732–733
program execution, 735
sessions, 736–737
spelling, 736
strings, 738–743
URLs, 743
variables, 62–66, 743–745
PHP help, 25
with syntax errors, 654
Web sites for, 7, 660
mail() function, 327
mktime() function, 249
regular expressions, 249
setup for mail, 326
starting tutorial, 249
string manipulation functions, 248
791
PHP help
Index
PHP help (continued)
URL function, 238
variables, 248
PHP5 (Hypertext Preprocessor) program. See also
variables
adding to Apache program, 10–11
advantages, 82, 763
browser’s handling of, 34
“cheat sheet” quick reference, 703–706
compiling with GD, 194
configuring, 733–735, 776
configuring for using MySQL, 16
constants, 37–38
cookie tracking, 399–402
database specificity problem, 763
e-mailing, setting up for, 325–326
HTML in, 30, 33, 34–37
installing
caution on use of automatic PHP installer, 772
with Linux, 776
with Windows, 772–773
logins with, 370–375
popularity and flexibility, 6–7
role as component of AMP module, 5–6
session tracking, 376–382
syntax rules, 30–31, 703
text editor for, 30
php5ts.dll file, 773
PHPBuilder, 659–660
PhpED text editor, 755, 756–757
PHPEdit text editor, 654, 755, 756–757
php.ini-dist file, 773
php.ini file
commonly changed settings, 14–16
configuring for e-mailing, 326
configuring for GD, 194
configuring for MySQL use with PHP5, 16
cookie longevity setting, 50
forcing passage of variables through cookies, 47
register_globals in, 15, 41, 44, 295, 330, 353,
655–656
renaming at installation with Windows, 772–773
php.ini-recommended file, 773
PHPMyAdmin, 109–110, 163, 166–168, 484, 524
PHPTriad (AMP installer), 8
pipes (||) in place of logical operator or, 79
PNG files
imagecreatefrompng() function, 207
imagepng function, 207
polls/surveys, 563, 639
polygons, in PHP with GD, 194
popularity of sites, determination from logs of activity,
641, 651–652
pos() array function, 78
POSIX (Portable Operating System Interface), 624
$_POST global array, 140–141, 159, 161
POST method, 139, 475, 655–656
postcard.php file, 327–328, 329, 330, 333,
334–335, 341–342, 346, 350–355
PostgreSQL databases, supported by third-party
hosts, 760
poweredit.php file, 301–305
precision, floating-point numbers in PHP, 15
preg_match(), 624
preg_replace(), 624, 625
PREV (Previous Page) button, 586–590
pricing considerations
for online selling site, 562–563
when hiring third-party host, 761–762
PRIMARY KEY keyword, 421
primary keys, 90, 169, 277, 279, 421
composite, 279
NULL as, 296
returning with mysql_insert_id(), 169
print(), 78
print_r(), 69, 140, 195
privacy issues for online selling, 561
private variables, 82
products, considerations for online selling, 518, 563
products table, 519, 522, 524
products.php file, 519, 524–525
producttest.php file, 525–527
programs. See coding practices; Comic Book Fan
Web site project; Movie Review Web site project;
software
promotional items, considerations for online selling,
518
protected variables, 82
public variables, 82
Q
queries
inserting multiple rows, 297
of multiple tables, 298
mysql_query(), 92, 97, 104, 298, 576
returning results from, 93
query strings in PHP variables, 42
792
PHP help (continued)
quickmsg.php file, 494, 496
quote capability, 639
R
\r\n carriage return and new line, 334
radio buttons, radio fields, 53, 145–148, 322
rand() function, 40
range in pagination, 586
RDBMS (relational database management systems).
See also databases, relational
capable of relationships between tables, 129
creating in MySQL, 285–289
design considerations, 279–283
expandable after initial creation, 276–277
keys, 277
MSSQL databases, supported by third-party hosts, 760
MySQL as, 7, 85, 86, 129, 170
normalization, 278, 283
placing datatypes into empty cells, 284
referential integrity, 278
relationships, 277–278
standardization, 283–284
for storage of discrete but linkable information, 85
storage into tables with fields (databases), 86
table joining for maximum efficiency, 7
table linking with primary/foreign keys, 170
records
counting with sizeof() function, 133
deleting, 178–183
deleting, and referential integrity considerations, 278
editing, 183–191
inserting into databases, 166–170
inserting in relational databases, 170–177
redirect($url), 431, 584
redirections with http.php file, 425, 584
referential integrity
information Web site, 278
of relational databases, 278
“reverse,” 298, 299–300
regex or regexp (regular expressions), 240, 248–250,
568, 624–628
register_globals
caution on use, 15, 41, 44, 295, 330, 353, 655–656
information (Web site for), 295
register.php file, 378–382
registration database, 375
registration page, 378–382
regular expressions, 240, 248–250, 568, 624–628
relational databases. See databases, relational
relationships in relational databases, 277–278
remove.php file, 506, 511–513
repeating actions. See loops
replacement patterns, 626–628
Report Magic (Analog add-on), 647
$_REQUEST, 45
require() function, 159, 303, 338
require_once() function, 440, 451
resource information. See Web sites for resources
returns policy considerations for online selling, 561
reusable mail class, 355–362
reverse duplication, 317
reverse referential integrity, 298, 299–300
reviewarticle.php, 463–466
rounding decimals up/down, 40, 304
rows
alternating background colors, 319
deleting matching in joined tables, 298
fetching with mysql_fetch_rows(), 93, 303
foreach() applying command to results set,
102–104
inserting multiple, 297
reverse duplication of data, 317
SELECT FOUND_ROWS(), 587, 588
rsort(array) function, 69
S
scalability (expandability) of databases, 276
screen formatting with forum_styles.css file, 574
screen size, of users’ monitors, in logs of Web site
activity, 651
script. See code
to denote PHP
code in HTML documents, 78
search capability on online selling site, 562
search engines and keyword searches, 652
searching tables by indexes (keys), 90, 169
search.php file, 430, 477–478, 633–634, 637–638
Second Normal Form (2NF), 283
security considerations
cookies, 49–50, 370
drawbacks of logins with PHP, 375
drawbacks to using .htaccess files, 370
e-mail encryption with fingerprint or hash, 352
immediate removal of administrator’s password from
server, 420
MySQL users and privileges settings, 24–25
793
security considerations
Index
security considerations (continued)
passing passwords with sessions, 47–49, 365, 395
requesting confirmation of e-mail subscriptions, 507
Web site for resources, 592
SELECT
for choosing data, 92
displaying list from which user chooses element, 144
with LEFT JOIN, 108–109
linking two tables, 277
name() attribute, 322
referencing multiple tables, 105–107, 317
sorting with, 303
syntax and parameters overview, 99–102
WHERE clause
AS clause disallowed, 99
for distinguishing between two tables, linking
common fields, 105–107, 109
equals sign and angle brackets as comparison
operators, 100
examples from Movie Review Web site project,
99–100, 102, 126
for joining tables, 320
LIMIT for limiting number of records returned, 177
with MATCH, 638
requirement with UPDATE, 183
in UPDATE queries, 298–299
select fields/drop-down boxes (input field type on
HTML forms), 53
SELECT FOUND_ROWS(), 587, 588
select2.php file, 104, 106, 108
select.php file, 100–102
self-posting forms, 493
selling over the Internet. See online selling from
Comic Book Fan site
send() function, 359–361, 496
sendconf.php file, 343, 351–352
sendmail, 326
sendmail_from, 326
sendmail_path, 326
sendmail.php file, 327, 328, 330, 332–334,
335–336, 340
servers
Apache as, 771
connecting to, 93–94, 303, 316, 338
control and access considerations when hiring
third-party host, 760–761
for e-mailing, 325–326
error notification by, 252
session_destroy(), 435
session_fileunset(), 56
sessions. See also logins
allowing access to session variables, 429
described, 370
ending and removing login data, 435
“headers already sent” (PHP error message),
49, 52, 657
passing of variables, 47–49, 704
PHP functions for handling, 736–737
security considerations, 47–49, 365, 395
settings for PHP, 16
tracking with PHP and MySQL, 376–382
Web site for resource, 429
session_start() function, 49, 429, 435, 440
session_unset(), 435
SET keyword, 298
setcookie() function, 50
setcookie.php file, 400
setcookie_pw.php file, 400, 401
setcookie_un.php file, 400, 401
setup.php file, 570–575
shipping costs, 533–534, 557–558
shopping cart programs. See also online selling from
Comic Book Fan site
third-party ready-made, 519
showComments(), 428
showimage.php file, 206, 208–210, 212–213,
217, 220
showTopic(), 586–587, 626
sizeof() function, 133
smallint(length), 87
smilies, 638
smoothing images with imagefilter() function, 208
SMTP (Simple Mail Transport Protocol) service, 326
smtp_port, 326
software. See also coding practices
help with syntax errors, 654
open source, 4–5
PHPMyAdmin, 109–110
PHPMyAdmin, 109–110, 163, 166–168, 484, 524
third-party access and error log analyzers, 646–650
third-party ready-made shopping cart programs, 519
sort(array) function, 69
sorting
arrays in PHP, 69
data by columns, 316, 318
lists with arrays, 70–74
with SELECT, 303
sorting.php file, 69
794
security considerations (continued)
spaces, eliminating leading or trailing with trim()
function, 238
spam, ethical considerations, 514, 561
and tags, 429
special characters
in HTML htmlspecialchars(), 429, 452
in URLs, 45–46
spell checking, 562
spelling functions in PHP, 736
SQL date and time functions (Web site for resource),
250
SQL use of indexes (Web site for resource), 421
SQL_CALC_FOUND_ROWS, 587
sql.php file, 483–485
squares, in PHP with GD, 194
SSH server access, considerations when hiring thirdparty
host, 760–761
startform.php file, 152–153
storage engines for MySQL tables, 91–92
strings
capitalizing with strtoupper() function, 150
parsing with ereg() function, 249
PHP functions for handling, 738–743
replacing with str_replace() function, 262, 263
testing for, 247
testing if empty, 238–239
str_replace() function, 262, 263
strtoupper() function, 150
studlyCaps, 81
submit buttons, 139–140, 149
surveys/polls, 563, 639
switch() function
compared to if/else(), 440
defining on query string parameter, 189
determining button click, 295
displaying custom error message, 256
displaying or sending error messages, 266
as filter, 202
illustrating flexibility, 434
processing multiple cases, 595–596
reminder to close, 437
syntax
of arrays, 67–69
MySQL, 92
PHP, 30–31, 703
syntax errors
help from software, 654
troubleshooting, 654–655, 656
systems for Web site management, 416
T
table1.php file, 112, 114
table2.php file, 116, 117–119, 120–121
table3.php file, 121
tables. See also databases, relational
aliases for, 317
alternating colors of row backgrounds, 319
atomicity of cells, 279
considerations for placement in databases, 484
creating for Comic Book Fan Web site project,
279–283, 286–289
creating with foreach() function, 102–104
defining headings, 111–114
described, 86
foreign, 277
hyperlinks in, 120–122
of images, 196–202
joining
with INNER JOIN function, 495
with JOIN function, 107–108, 316
with LEFT join function, 109
with WHERE clause of SELECT command, 320
linking, 117–120
for mailing lists, 483–485
multiple, referencing in SELECT statements,
105–107, 317
naming, standards (design rules) for, 283–284, 317
populating, 94–98, 114–120, 122–123, 129–130,
319
sending to browser, 116
storage engines, 91–92
transaction-safe (TSTs) and non-transaction-safe
(NTSTs), 91
tags
alternates to, 78
parsing in PHP, 15
tarballs
httpd-2.0.x.tar.gz file, 775
mysql-4.0.x.tar.gz file, 774
php-5.0.x.tar.gz file, 776
TCP/IP requirement, 17, 771
telemarketing, ethical considerations, 561
telnet server access, considerations when hiring
third-party host, 760–761
template.php. file, 370–371, 372
TEMPORARY keyword, 288–289
ternary comparison operators, 150
testcookie.php, 401
795
testcookie.php
Index
testing. See also debugging
Apache + PHP installation, 13–14
directory/document root for Apache, 11–13
live versus off-line, 6
MySQL installation, 17–19
text(), 87
text
adding to images, 214–218
converting to readable on HTML pages, 429
displaying in browsers, 703
formatting with HTML inside PHP, 36
matching with regular expressions, 624–628
trimming (shortening), 426
text boxes, 139–140, 194
text editors, 755
text (input field type on HTML forms), 53
TextPad text editor, 755, 756–757
thanks.php file, 501–502, 503, 509–511
Third Normal Form (3NF), 283
$this->variable command in OOP, 81
thumbnails of images, 220–225
time(), 87
time/date/calendar functions of PHP, 712–716
timestamp function, 249–250
tinyblob, 88
tinyint(length), 87, 228
tinytext, 88
titles of pages, dynamic, 149–150
tooltips, 121
top.php file, 657
transact-admin.php file, 593–595
transact-affirm.php file, 602–604, 623
transact-article.php file, 437–444
transact-post.php file, 596–602
transact-user.php file, 431, 475
transaction pages, 291, 294–301
transaction-safe (TSTs) tables, 91
trapping errors. See error handling in PHP
trim() function, 238, 248
trimBody(), 426–427
troubleshooting. See also debugging
with echo function, 271, 658–659
empty variables
case, consistency, and validity of names, 656
GET versus POST methods, 655–656
register_globals setting, 15, 41, 44, 295, 330,
353, 655–656
uncleared variables from previous session, 656–657
font not installed on server, 215
“headers already sent” (PHP error message),
49, 52, 657
importance, 251, 272
importance of coding practices, 31
installation problems, 653
PHP parse errors, 272, 653–654
syntax errors, 654–655
try/catch method of handling PHP Exceptions,
269–270
U
ucfirst() function, 150
ucwords() function, 133
UltraEdit-32 text editor, 654, 755, 756–757
underscore (_) for PHP variables, 38
UNIQUE data, 300
unique fields, 90
UNIQUE KEY keyword, 421
UNIX-like systems. See Linux
UNIX_TIMESTAMP(), 250
unlogged_admin.php file, 404
unlogged_user.php, 377, 382
UPDATE, 92, 123, 183, 298, 539
update_account.php file, 386–388
updates, logging, settings for MySQL, 23
update_user.php, 406–409
upload_image.htm file, 197, 199–200
upper case for SQL words, 114
urlencode() function, 45–46, 238
URLs
caution on disadvantages for passing variables, 42
caution on having script parameters in, 139
concatenating into confirmation e-mails, 507–508
as links to products, 530
passing variables, 42–46, 532, 539, 704
PHP functions for handling, 743
special characters in, 45–46
user authentication packages of PEAR, 769
User Control Panels, considerations when hiring
third-party host, 761
user login system
allowing administrator edits of accounts, 402–403, 412
allowing user edits of accounts, 383–385
creating, 376–382
creating accounts, 435
editing user accounts, 385–399
user profiles, 639
user setup, MySQL program, 19–20
useraccount.php file, 448–453, 457, 612–616
796
testing
user_info table, 375, 376
user_login.php file, 383–384
usernames
checking against database, 383–384
displaying at login, 382
MySQL server, 93
requiring for access to folder, 366
storing in sessions, 47–49
userOptionList() function, 617
user_personal.php file, 383, 384–385
user.php file, 497–498, 502–503, 504–505, 509, 513
users. See also cookies; user login system
anonymous, 369
authentication for BBS visits, 568, 592–593
getting them to return. See content management system
(CMS)
privileges settings for MySQL program, 24–25
validating input from. See errors in user input
user_transact.php file, 499–501, 505–509, 513
V
validating user input, 227, 229
+$-value functions, 79
Vander Veer, Emily A., 351
varchar(length), 86, 284
variables
caution on register_globals setting, 15, 41, 44,
295, 330, 353, 655–656
arrays, 67–74
assigning values, 703
case-sensitivity, 38
checking for set condition, 322
functions, 62–66, 743–745
if/else statements, 59–60
if() statements, 57–59
includes statements, 60–62
incrementing or decrementing automatically, 79, 296
naming, 131
overview, 38–40
passing with cookies, 49–53
passing between pages, 40–41
passing through forms, 53–57, 704
passing through sessions, 47–49, 704
passing through URLs, 42–46, 704
public, private, and protected, 82
settings, 15
troubleshooting with echo function, 271
viewarticle.php file, 469–471
viewforum.php file, 628–630
viewpostcard.php file, 345–346
viewtopic.php file, 630–631
W
W3 Security FAQ Web site, 50
warnings (runtime), 261
warranty policy considerations for online selling, 561
watermarks, 218–220
WBMP (Wireless Bitmap) files, 201
Web pages. See pages; Web site creation; Web sites
for resources
Web site creation. See also BBS (bulletin board
system) for Comic Book Fans; Comic Book Fan
Web site project; content management system
(CMS); logs of Web site activity; Movie Review
Web site project
considerations for professional look, 562
getting started, 275–276
uses for e-mail, 325
uses and ethical considerations for mailing lists,
481–482, 514–515
Web sites for resources
alistapart, 568
AMP installers, 8
Analog and Report Magic add-on, 647
Apache, 25, 660
AWStats, 649
BDB (BerkeleyDB), 92
Boutell.com, 193
Cart32 shopping cart software, 519
CSS (cascading style sheets), 568
date display functions, 429
downloadable code for Comic Book Fan Web site
project, 291
downloadable postcard images, 337
e-mail encryption with fingerprint or hash, 352
Foxserv, 8
full-text indexed fields, 478
Fulltext indexes, 638
GD (Graphics Draw) library, 193
Gifts for Engineers, 518
HTML forms, 452
HTML references, 138
HTTP Analyze, 650
imagefilter function syntax, 208
InnoDB, 91
IRC channels, 660
keys (indexes), 637
MySQL, 7, 660
797
Web sites for resources
Index
Web sites for resources (continued)
Netcraft, 6
open source programs, 4
output buffer functions, 657
pattern modifiers, 626
PCRE (Perl Compatible Regular Expressions), 628
PEAR (PHP Extension and Application Repository), 764
PHP, 7, 660
PHP mail() function, 327
PHP mktime() function, 249
PHP regular expressions, 249
PHP setup for mail, 326
PHP starting tutorial, 249
PHP string manipulation functions, 248
PHP URL function, 238
PHP variables, 248
PHPBuilder, 659–660
PHPEdit, 654
PHPMyAdmin, 110
PHPTriad, 8
referential integrity and foreign keys information, 278
register_globals information, 295
regular expressions, 624, 625, 628
Report Magic (Analog add-on), 647
security issues, 592
sessions, 429
SQL date and time functions, 250
SQL use of indexes, 421
text editors, 755
third-party hosts, 762
UltraEdit, 654
W3 Security FAQ, 50
Webalizer, 646
webmonkey, 568
WebTrends, 648
WROX companion site, 659
wrox.com, 163
XAMPP, 8
Zeldman, Jeffrey, 568
Webalizer (third-party software for log analysis),
646–647
WebMasters. See administrators
WebTrends (third-party software for log analysis), 648
WHERE clause of SELECT statement
AS clause disallowed, 99
for distinguishing between two tables, linking common
fields, 105–107, 109
equals sign and angle brackets as comparison
operators, 100
examples from Movie Review Web site project, 99–100,
102, 126
for joining tables, 320
LIMIT for limiting number of records returned, 177
with MATCH, 638
requirement with UPDATE, 183
in UPDATE queries, 298–299
while() statement
error trapping, 271
executing repeatedly while given condition is true,
74–75
filling table with data, 115
limiting conditions of query, 102
list numbering example, 75–77
retrieving desired records and fields, 104
Windows
installing Apache, 771–772
installing MySQL, 773–774
installing PHP, 772–773
WordPad text editor, 755, 756–757
workflow applications, requiring input from various
parties, 340
WROX companion site, 659
WROX Web site, 163
X
XAMPP (AMP installer), 8
Y
year(length), 88
Z
Zeldman, Jeffrey (Web site for resource), 568
Zero Form, 283
798

No comments: