All of the following functions are part of the numerous functions that make up the PHP language. These really are just a small number of the PHP functions; they are the ones I use on a regular basis. Depending on the types of things you'll be doing with PHP, you might not need more functions, but please visit the PHP manual at http://www.php.net/manual/ and familiarize yourself with what is available.
Numerous PHP functions are available for use with arrays. Only a few are noted here—those that I find absolutely essential, and those that form a foundation of knowledge for working with arrays.
The array() function allows you to manually assign values to an array. Here is the syntax of the array() function:
$array_name = array("val1", "val2", "val3", ...);
The array_push() function allows you to add one or more elements to the end of an existing array. Its syntax is
array_push($array_name, "element 1", "element 2", ...);
The array_pop() function allows you to take (pop) off the last element of an existing array. Its syntax is
The array_unshift() function allows you to add elements to the beginning of an existing array. Its syntax is
array_unshift($array_name, "element 1", "element 2", ...);
The array_shift() function allows you to take (pop) off the first element of an existing array. Its syntax is
array_shift($array_name);
The array_merge() function allows you to combine two or more existing arrays. Its syntax is
array_merge($array1, $array2, ...);
The array_keys() function returns an array of all the key names in an existing array. Its syntax is
array_keys($array_name);
The array_values() function returns an array of all the values in an existing array. Its syntax is
The count() function counts the number of elements in a variable. It's normally used to count the number of elements in an array, because any variable that is not an array has only one element—itself.
In the following example, $a is assigned a value equal to the number of elements in the $colors array:
$a = count($colors);
If $colors contains the values blue, black, red, and green, $a will be assigned a value of 4.
The each() and list() functions usually appear together, in the context of stepping through an array and returning its keys and values. Here is the syntax for these functions:
each(arrayname); list(val1, val2, val3, ...);
For example, when you submit an HTML form via the GET method, each key/value pair is placed in the global variable $_GET. If your form input fields are named first_name and last_name and the user enters values of Joe and Smith, the key/value pairs are first_name/Joe and last_name/Smith. In the $_GET array, these variables are represented as the following:
$_GET["first_name"] // value is "Joe" $_GET["last_name"] // value is "Smith"
You can use the each() and list() functions to step through the array in this fashion, printing the key and value for each element in the array:
The reset() function rewinds the pointer to the beginning of the array. Its syntax is
reset($array_name);
Numerous PHP functions exist for connecting to and querying a MySQL server. Following are some basic functions and their syntax. See the PHP manual at http://www.php.net/manual/ for a complete listing of MySQL functions—there are plenty!
This function opens a connection to MySQL. It requires a server name, username, and password:
This function selects a database on the MySQL server for use by subsequent queries. It requires a valid established connection:
$db = mysql_select_db("myDB", $connection);
This function issues the SQL statement. It requires an open connection to the database:
$sql_result = mysql_query("SELECT * FROM SOMETABLE",$connection);
This function returns a meaningful error message when something goes wrong with your connection or query. It's normally used in the context of the die() function, like this:
$sql_result = mysql_query("SELECT * FROM SOMETABLE",$connection)
or die(mysql_error());
The basic PHP date and time functions let you easily format timestamps for use in database queries and calendar functions, as well as for simply printing the date on an order form receipt.
The date() function returns the current server timestamp, formatted according to a given set of parameters. Its syntax is
date(format, [timestamp]);
If the timestamp parameter is not provided, the current timestamp is assumed. Table B.7 shows the available formats.
|
Character |
Meaning |
|---|---|
|
a |
Prints "am" or "pm" |
|
A |
Prints "AM" or "PM" |
|
h |
Hour in 12-hour format (01 to 12) |
|
H |
Hour in 24-hour format (00 to 23) |
|
g |
Hour in 12-hour format without a leading zero (1 to 12) |
|
G |
Hour in 24-hour format without a leading zero (0 to 23) |
|
i |
Minutes (00 to 59) |
|
s |
Seconds (00 to 59) |
|
Z |
Time zone offset in seconds (-43200 to 43200) |
|
U |
Seconds since the Epoch (January 1, 1970 00:00:00 GMT) |
|
d |
Day of the month in two digits (01 to 31) |
|
j |
Day of the month in two digits without a leading zero (1 to 31) |
|
D |
Day of the week in text (Mon to Sun) |
|
l |
Day of the week in long text (Monday to Sunday) |
|
w |
Day of the week in numeric, Sunday to Saturday (0 to 6) |
|
F |
Month in long text (January to December) |
|
m |
Month in two digits (01 to 12) |
|
n |
Month in two digits without a leading zero (1 to 12) |
|
M |
Month in three-letter text (Jan to Dec) |
|
Y |
Year in four digits (2000) |
|
y |
Year in two digits (00) |
|
z |
Day of the year (0 to 365) |
|
t |
Number of days in the given month (28 to 31) |
|
S |
English ordinal suffix (th, nd, st) |
The checkdate() function validates a given date. Successful validation means that the year is between 0 and 32767, the month is between 1 and 12, and the proper number of days is in each month (leap years are accounted for). Its syntax is
checkdate(month, day, year);
The mktime() function returns the Unix timestamp as a long integer (in the format of seconds since the Epoch, or January 1, 1970) for a given date. Thus, the primary use of mktime() is to format dates in preparation for mathematical functions and date validation. Its syntax is
mktime(hour, minute, second, month, day, year);
The time() function returns the current system time, measured in seconds since the Epoch. The syntax of time() is simply
You could get a result such as 958950466.
Using microtime() adds a count of microseconds, so instead of just receiving a result like 958950466, you would get a result like 0.93121600 958950466, at the exact moment you asked for the time since the Epoch (this includes both seconds and microseconds).
The built-in file system functions can be very powerful tools—or weapons, if used incorrectly. Be very careful when using file system functions, especially if you have PHP configured to run as root or some other system-wide user. For example, using a PHP script to issue an rm -R command while at the root level of your directory structure would be a very bad thing.
Like the shell commands of the same name, the chmod(), chgrp(), and chown() functions modify the permissions, group, and owner of a directory or file. Here is the syntax of these functions:
chmod("filename", mode);
chmgrp("filename", newgroup);
chown("filename", newowner);
In order to change permissions, groups, and owners, the PHP user must be the owner of the file, or the permissions must already be set to allow such changes by that user.
The copy() function works much like the cp shell command: It needs a filename and a destination in order to copy a file. The syntax of copy() is
copy("source filename", "destination");
The PHP user must have permission to write into the destination directory, or the copy() function will fail.
The fopen() function opens a specified file or URL for reading and/or writing. The syntax of fopen() is
fopen("filename", "mode")
To open a URL, use http:// or ftp:// at the beginning of the filename string. You can open URLs only for reading, not writing.
If the filename begins with anything else, the file is opened from the file system and a file pointer to the opened file is returned. Otherwise, the file is assumed to reside on the local file system.
The specified mode determines whether the file is opened for reading, writing, or both. Table B.8 lists the valid modes.
|
Mode |
Description |
|---|---|
|
r |
Read-only. The file pointer is at the beginning of the file. |
|
r+ |
Reading and writing. The file pointer is at the beginning of the file. |
|
w |
Write-only. The file pointer is at the beginning of the file, and the file is truncated to zero length. If the file does not exist, attempt to create it. |
|
w+ |
Reading and writing. The file pointer is at the beginning of the file, and the file is truncated to zero length. If the file does not exist, attempt to create it. |
|
a |
Write-only. The file pointer is at the end of the file (it appends content to the file). If the file does not exist, attempt to create it. |
|
a+ |
Reading and writing. The file pointer is at the end of the file (it appends content to the file). If the file does not exist, attempt to create it. |
|
x |
Create and open a file for writing only. The file pointer is at the beginning of the file. Will fail if the file already exists. |
|
x+ |
Create and open a file for reading and writing. The file pointer is at the beginning of the file. Will fail if the file already exists. |
Use the fread() function to read a specified number of bytes from an open file pointer. Its syntax is
fread(filepointer, length);
The fputs() function writes to an open file pointer. Its syntax is
fputs(filepointer, content, [length]);
The file pointer must be open in order to write to the file. The length parameter is optional. If it isn't specified, all specified content is written to the file.
Use the fclose() function to close an open file pointer. Its syntax is
fclose(filepointer);
Like the mkdir shell command, the mkdir() function creates a new directory on the file system. Its syntax is
mkdir("pathname", mode);
The PHP user must have write permission in the specified directory.
As its name suggests, the rename() function attempts to give a new name to an existing file. Its syntax is
rename("oldname", "newname");
The PHP user must have permission to modify the file.
Like the rmdir shell command, the rmdir() function removes a directory from the file system. Its syntax is
rmdir("pathname");
The PHP user must have write permission in the specified directory.
The built-in functions for sending specific HTTP headers and cookie data are crucial aspects of developing large web-based applications in PHP. Luckily, the syntax for these functions is quite easy to understand and implement.
The header() function outputs an HTTP header string, such as a location redirection. This output must occur before any other data is sent to the browser, including HTML tags.
| Note |
This information bears repeating: Do not attempt to send information of any sort to the browser before sending a header(). You can perform any sort of database manipulations or other calculations before the header(), but you cannot print anything to the screen—not even a newline character. |
For example, to use the header() function to redirect a user to a new location, use this code:
header("Location: http://www.newlocation.com");
exit;
| Tip |
Follow a header() statement with the exit command. This ensures that the code does not continue to execute. |
The setcookie() function sends a cookie to the user. Cookies must be sent before any other header information is sent to the web browser. The syntax for setcookie() is
setcookie("name", "value", "expire", "path", "domain", "secure");
For example, you would use the following code to send a cookie called username with a value of joe that is valid for one hour within all directories on the testcompany.com domain:
setcookie("username","joe", time()+3600, "/", ".testcompany.com");
The PHP mail function makes the interface between your HTML forms and your server's outgoing mail program a snap!
If your server has access to sendmail or an external SMTP server, the mail() function sends mail to a specified recipient. Its syntax is
mail("recipient", "subject", "message", "mail headers");
For example, the following code sends mail to <julie@thickbook.com>, with a subject of "I'm sending mail!" and a message body saying "PHP is cool!" The From line is part of the additional mail headers:
mail("julie@thickbook.com", "I'm sending mail!",
"PHP is cool!", "From: youremail@yourdomain.com\n");
Because I have very little aptitude for mathematics, I find PHP's built-in mathematical functions to be of the utmost importance! In addition to all the functions, the value of pi (3.14159265358979323846) is already defined as a constant in PHP (M_PI).
The ceil() function rounds a fraction up to the next higher integer. Its syntax is
ceil(number);
The decbin() and bindec() functions convert decimal numbers to binary numbers and binary numbers to decimal numbers, respectively. The syntax of these functions is
The dechex() and hexdec() functions convert decimal numbers to hexadecimal numbers and hexadecimal numbers to decimal numbers, respectively. The syntax of these functions is
dechex(number); hexdec(number);
The decoct() and octdec() functions convert decimal numbers to octal numbers and octal numbers to decimal numbers, respectively. The syntax of these functions is
decoct(number); octdec(number);
The floor() function rounds a fraction down to the next lower integer. Its syntax is
floor(number);
The number_format() function returns the formatted version of a specified number. Its syntax is
number_format("number", "decimals", "dec_point", "thousands_sep");
For example, to return a formatted version of the number 12156688 with two decimal places and a comma separating each group of thousands, use
echo number_format("12156688","2",".",",");
The result is 12,156,688.00.
If only a number is provided, the default formatting does not use a decimal point and puts a comma between every group of thousands.
The pow() function returns the value of a given number raised to the power of a given exponent. Its syntax is
pow(number, exponent);
The rand() function generates a random value from a specific range of numbers. Its syntax is
rand(min, max);
The die() and exit functions provide useful control over the execution of your script, offering an escape route for programming errors. Other functions have found their way into this miscellaneous category.
The die() function outputs a given message and terminates the script when a returned value is false. Its syntax is
die("message");
For example, you would use the following code to print a message and stop the execution of your script upon failure to connect to your database:
$connection = mysql_connect("servername", "username", "password")
or die ("Can't connect to database.");
The exit statement terminates the execution of the current script at the point where the exit statement is made.
The sleep() and usleep() functions put a pause, or a delay, at a given point in the execution of your PHP code. The syntax of these functions is
sleep(seconds); usleep(microseconds);
The only difference between sleep() and usleep() is that the given wait period for sleep() is in seconds, and the wait period for usleep() is in microseconds.
The uniqid() function generates a unique identifier with a prefix if you want one. Its syntax is
uniqid("prefix");
That's boring, though. Suppose you want a unique ID with a prefix of phpuser. You would use
$id = uniqid("phpuser");
echo "$id";
and you would get something like phpuser38b320a6b5482.
But if you use something really cool like
$id = md5(uniqid(rand())); echo "$id";
you would get an ID like 999d8971461bedfc7caadcab33e65866.
You can use PHP's built-in program execution functions to use programs residing on your system, such as encryption programs, third-party image manipulation programs, and so forth. For all program execution functions, the PHP user must have permission to execute the given program.
The exec() function executes an external program. Its syntax is
exec(command, [array], [return_var]);
If an array is specified, the output of the exec() function will append to the array. If return_var is specified, it will be assigned a value of the program's return status.
For example, you would use the following code to perform a ping of a server five times and print the output:
$command = "ping -c5 www.thickbook.com";
exec($command, $result, $rval);
for ($i = 0; $i < sizeof($result); $i++) {
echo "$result[$i]<br>";
}
Like the exec() function, the passthru() function executes an external program. The difference between the two is that passthru() returns the raw output of the action. The syntax of passthru() is
passthru(command, return_var);
If return_var is specified, it will be assigned a value of the program's return status.
The system() function executes an external program and displays output as the command is being executed. Its syntax is
system(command, [return_var]);
If return_var is specified, it will be assigned a value of the program's return status.
For example, you would use the following code to perform a ping of a server five times and print the raw output:
The ereg_replace() and eregi_replace() functions replace instances of a pattern within a string and return the new string. The ereg_replace() function performs a case-sensitive match, and eregi_replace() performs a case-insensitive match. Here is the syntax for both functions:
ereg_replace(pattern, replacement, string); eregi_replace(pattern, replacement, string);
For example, you would use the following code to replace "ASP" with "PHP" in the string "I really love programming in ASP!"
$old_string = "I really love programming in ASP!";
$new_string = ereg_replace("ASP", "PHP", $old_string);
echo "$new_string";
If "ASP" is mixed case, such as "aSp", use the eregi_replace() function:
$old_string = "I really love programming in aSp!";
$new_string = eregi_replace("ASP", "PHP", $old_string);
echo "$new_string";
The split() function splits a string into an array using a certain separator (comma, colon, semicolon, and so on). Its syntax is
split(pattern, string, [limit]);
The limit is optional. If a limit is specified, the split() function stops at the named position—for example, at the tenth value in a comma-delimited list.
Session-Handling Functions
Session handling is a way of holding on to data as a user navigates your website. Data can be variables or entire objects. These simple functions are just a few of the session-related functions in PHP; see the PHP manual at http://www.php.net/ manual/ for more.
This section only scratches the surface of PHP's built-in string manipulation functions, but if you understand these common functions, your programming life will be quite a bit easier!
The addslashes() and stripslashes() functions are very important when inserting and retrieving data from a database. Often, text inserted into a database will contain special characters (single quotes, double quotes, backslashes, NULL) that must be escaped before being inserted. The addslashes() function does just that, using this syntax:
Similarly, the stripslashes() function returns a string with the slashes taken away, using this syntax:
stripslashes(string);
All three of these functions remove errant white space from a string. The chop() function removes white space from the end of a string, and ltrim() removes white space from the beginning of a string. The trim() function removes both leading and trailing white space from a string. Here is the syntax of these functions:
chop(string); ltrim(string); trim(string);
The echo() function returns output. The syntax of echo() is
echo (parameter 1, parameter 2, ...)
For example:
echo "I'm using PHP!"; // output is: I'm using PHP! echo 2+6; // output is: 8
The parentheses are not required when using echo.
The explode() function splits a string using a given separator and returns the values in an array. The syntax of explode() is
explode("separator", "string");
For example, the following code takes a string called $color_list, containing a comma-separated list of colors, and places each color into an array called $my_colors:
$color_list = "blue,black,red,green,yellow,orange";
$mycolors = explode(",", $color_list);
Conversely, the implode() function takes an array and makes it into a string, using a given separator. The syntax of implode() is
implode("separator", "string");
For example, the following code takes an array called $color_list and then creates a string called $mycolors, containing the values of the $color_list array, separated by commas:
$mycolors = implode(",", $color_list);
The htmlspecialchars() and htmlentities() functions convert special characters and HTML entities within strings into their acceptable entity representations. The htmlspecialchars() function converts only the less-than sign (< becomes <), greater-than sign (> becomes >), double quotes ("" becomes "), and the ampersand (& becomes &).
The htmlentities() function converts the characters in the ISO-8859-1 character set to the proper HTML entity. Here is the syntax of these functions:
htmlspecialchars(string); htmlentities(string);
The nl2br() function replaces all ASCII newlines with the HTML line break (<BR>). The syntax of the nl2br() function is
The sprintf() function returns a string that has been formatted according to a set of directives, as listed in Table B.9. The syntax of sprintf() is
|
Directive |
Result |
|---|---|
|
% |
Adds a percent sign |
|
b |
Considers the string an integer and formats it as a binary number |
|
c |
Considers the string an integer and formats it with that ASCII value |
|
d |
Considers the string an integer and formats it as a decimal number |
|
f |
Considers the string a double and formats it as a floating-point number |
|
o |
Considers the string an integer and formats it as an octal number |
|
s |
Considers and formats the string as a string |
|
x |
Considers the string an integer and formats it as a hexadecimal number (lowercase letters) |
|
X |
Considers the string an integer and formats it as a hexadecimal number (uppercase letters) |
sprintf(directives, string);
For example, to turn the number 5 into $5.00 (five dollars), use:
$newnumber = sprintf("%0.02f", 5);
The strtolower() function returns a given string with all alphabetic characters in lowercase. Its syntax is
strtolower(str);
The strtoupper() function returns a given string with all alphabetic characters in uppercase. Its syntax is
strtoupper (str);
The substr() function returns a portion of a string, given a starting position and optional ultimate length. Its syntax is
substr(string, start, [length]);
If the start position is a positive number, the starting position is counted from the beginning of the string. If the start position is negative, the starting position is counted from the end of the string.
Similarly, if the optional length parameter is used and is a positive number, the length is counted from the beginning of the string. If the length parameter is used and is a negative number, the length is counted from the end of the string.
For example:
The two basic variable functions, isset() and unset(), help you manage your variables within the scope of an application.
The isset() function determines whether a variable exists. The unset() function explicitly destroys the named variable. Here is the syntax of each:
isset(var); unset(var);
The isset() function returns true if the variable exists and false if it does not.