. 27
( 132 .)


if (is_array($var))
//process array

Some functions will return a value if there is a value to be returned, and will
return FALSE if there is no value to be returned. A good example of this is the
mysql_fetch_array() function. This function will grab rows from a result set
returned by a query, as long as there are results to grab. When no more rows are to
be had it returns FALSE. As you saw in Chapter 5, this is very helpful for looping
through all rows returned by a query.

$result = mysql_query(“select * from my_table”) or
die ( mysql_error() );
while($row = mysql_fetch_array($result))
//process row

Finally, a function will occasionally return no value at all. This is rare, as most
functions at least return TRUE on success and FALSE on failure. If a function does
not return any value, the keyword ˜void™ again is used in the documentation to
tell you so:

void function_name(arg1, arg2, ...)

Function Documentation
As we say repeatedly throughout this book, the PHP online manual is your friend.
The documentation team is amazing, and we really believe that the quality of the
online manual is one of the reasons for the success of the language. As we cannot
realistically cover every PHP function in this book, you will need to consult the
online manual or one of the excellent PHP encyclopedias that exist (try PHP
Functions: Essential Reference by Zak Greant and others). For that reason, we want
to take a minute to go over the way in which it presents the functions.
A typical manual reference will look something like this:

int mysql_affected_rows ([int link_identifier])

This function returns the number of rows affected by an update, insert, or
delete query. Looking at this, you can see that the first portion (int) indicates the
variable type that will be returned. This can be any of the variable types or void
(meaning that the function will return nothing). Then comes a list of arguments in
Chapter 6: PHP™s Built-in Functions 137

parentheses. The type of argument is listed as well as what it represents. Note that
optional arguments are placed in brackets. In the preceding code sample, therefore,
the function requires no arguments but has one optional argument: the connection
identifier grabbed from mysql_connect().
In the preceding example, if you pass an argument, it had better be an integer. If
you were to use an array, for example, you would get an error.

Important PHP Functions
In this section we will attempt to break down PHP functions into logical groupings.
Along the way we will cover the functions used in the applications presented in this

String handling functions
In creating Web-based applications, string handling and manipulation are among
the most critical tasks of the language you work with. Text cleanup and validation
are extremely important, and good Web middleware will make working with text
relatively easy. PHP excels in this department: It contains built-in functions that
cover most anything you™d want to do to text.
In fact, far more string handling functions exist than we could cover here. At the
time this book was written, 88 string handling functions were listed on http://
www.php.net/manual/en/ref.strings.php. In this book we can cover only a
portion of these. We will cover all the string handling functions we used in the
course of creating the applications in Parts III and IV, and we will cover some other
notable functions that we didn™t have the opportunity to use.

We thought it would be nice to start with a function that clearly demonstrates why
PHP is so cool.

STRIP_TAGS() This function removes HTML and PHP tags.

string strip_tags (string str [, string allowable_tags])

One of the most important things you will need to do with every Web-based
application you write is make sure that the users of your Web pages haven™t passed
you malicious text. As we discuss in Chapter 8, if you™re not careful, you might find
your pages filled with HTML tags (<img>, <div>, and the like) or JavaScript code
that you don™t want. You could also find yourself in real trouble if some cracker
decides to litter your form fields with something like <script> alert(“you
138 Part II: Working with PHP

The strip_tags() function will remove all HTML and PHP tags, except for
those explicitly allowed in the second argument. If you want to allow <b> and <i>
tags, you can use this:

strip_tags($str, “<b><i>”)

ADDSLASHES() This function is intended to work with your database insert and
update queries.

string addslashes (string str)

If you take a look at a typical insert query you can see a potential problem:

insert into table_name(char_field, numeric_field)
values (˜$str™, $num);

What if the value in $str contains a contraction such as “ain™t”? You could get
an error because the apostrophe is going to confuse MySQL. You need to escape all
occurrences of single quotes (˜), double quotes (“), and NULLs in the string. For

$str1 = “let™s see”;
$str2 = “you know”;
$str1 = addslashes($str1);
$result = mysql_query(“insert into show_stuff
(stuff_desc, stuff_stuff) values(˜$str1™, ˜$str2™)”);
echo mysql_affected_rows();

So, given this potential problem, do you need to put all of your form-input
information through addslashes()? Not necessarily. It depends on the
magic_quotes_gpc setting in your php.ini file. If it is set to on, data that comes
from HTTP GET, HTTP POST, or cookies is automatically escaped, so you don™t need
to worry about putting the information through addslashes().

Make sure to check your magic_quotes settings in your php.ini file. Note
that if set to yes, magic_quotes_runtime will automatically add slashes
to data returned from queries and files. See Appendix Cfor more discussion
on magic_quotes settings.

STRIPSLASHES() This function reverses the operation of addslashes(). It returns
an unescaped string from which all backslashes have been removed.

string stripslashes (string str)
Chapter 6: PHP™s Built-in Functions 139

If you are writing code for distribution, where you won™t be able to know how
your user™s PHP installation is configured, you might want to use stripslashes()
and addslashes() in combination:

$var1 = $_GET[˜var1™];
$stripped_var = stripslashes($var1);
$slashed_var = addslashes($stripped_var);
$result = mysql_query(“insert into mytable (mycol) values

This code runs regardless of the setting of magic_quotes_gpc.
The following sections contain some more PHP string functions that are used in
this book.


string htmlentities (string string [, int quote_style [, string charset]])

string htmlspecialchars (string string [, int quote_style [, string charset]])

These two functions translate characters into their HTML escape codes. html
specialchars() translates only the characters that might be interpreted as markup
on an output page (namely &, <, >, ˜, and “), whereas htmlentities() translates
every character that has an HTML equivalent.


string crypt (string str [, string salt])

Given a string, this function returns a one-way hash of the string, using either
the optionally provided salt or a randomly generated one. Providing your own salt
allows reproducibility in testing and also allows you to specify the hashing algo-
rithm that™s used.


string trim (string str [, string charlist])

This function returns a string with all white space trimmed from the beginning
and end. With the second argument, you can specify an additional list of characters
to be trimmed off.


string str_repeat (string input, int multiplier)
140 Part II: Working with PHP

This function returns a string consisting of the input string concatenated to itself
the specified number of times.


mixed str_replace (mixed search, mixed replace, mixed subject)

Given three arguments as input, this function returns a string consisting of a
modified version of the third argument with every instance of the first argument
replaced by the second argument. This is a lightweight alternative to the regular
expression functions and should be used when the power of regular expressions is
not required.


string strchr (string subject, string search)

string strstr (string subject, string search)

string stristr (string subject, string search)

These functions behave identically, except that strchr() and strstr() are
case-sensitive and stristr() is case-insensitive. They search for the second argu-
ment in the first, and return the part of subject following the first instance of


int strlen (string str)

Given a string, this function returns a character count.


int strpos (string haystack, string needle [, int offset])

This function returns the position of the first occurrence of the string needle in
the string haystack, starting at the position in haystack specified by offset, or at 0
(the beginning of the string) if offset is not specified. If needle is not found, the
function returns FALSE.


int strrpos (string haystack, char needle)
Chapter 6: PHP™s Built-in Functions 141

This function behaves similarly to strpos(), but it returns the position of the
last occurrence of the search character. Note that with this function the string to be
found can only be a single character.


string strrev (string string)

This function reverses a string.


string substr (string string, int start [, int length])

This function returns a substring of the input string, delineated by the start and
length arguments. If length is absent, the substring will go to the end of the string.


string strtolower (string str)

string strtoupper (string str)

string ucfirst (string str)

string ucwords (string str)

These functions change the capitalization of alphabetic strings. strtolower()
and strtoupper() change the case of the entire string to lower or upper case,
respectively; ucfirst() capitalizes only the first character of the input string; and
ucwords() capitalizes the first character of each white space“delineated word in
the string ” to lower or upper case, respectively.

Just because we didn™t use them doesn™t mean you won™t. And again, it™s entirely


. 27
( 132 .)