Built-in Functions

The functions to be described in the following sections are just a small sampling of the numerous functions that make up the PHP language; they are the ones I use on a regular basis. Depending on what you'll be doing with PHP, you may or may not need more functions, but do visit the PHP manual, at http://www.php.net/manual/, and familiarize yourself with what is available.

Array Functions

Numerous PHP functions are available for use with arrays. Noted here are only those that I find absolutely essential, and those that form a foundation of knowledge for working with arrays.

array()

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", ...); 

For example, to create an array called $colors containing the values "blue", "black", "red", and "green", use the following:

 $colors = array("blue", "black", "red", "green"); 

array_push()

The array_push() function allows you to add one or more elements to the end of an existing array.

The syntax of the array_push() function is

 array_push($array_name, "element 1", "element 2", ...); 

For example, say you have an array that contains the elements "1" and "2" and you want to add the elements "3", "4", "5", and "cool" to it. You would use this snippet of code:

 $sample = array(1, 2); array_push($sample, 3, 4, 5, "cool"); 

You can use the example script below to print the "Before" and "After" versions of the $sample array:

 <?php $sample = array(1, 2); echo "BEFORE:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } reset($sample); array_push($sample, 3, 4, 5, "cool"); echo "<br>AFTER:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } ?> 

The script will print the following:

  • BEFORE:

    0:1

    1:2

  • AFTER:

    0:1

    1:2

    2:3

    3:4

    4:5

    5:cool

array_pop()

The array_pop() function allows you to take (pop) off the last element of an existing array.

The syntax of the array_pop() function is

 array_pop($array_name); 

For example, say you have an array that contains the elements "1", "2", "3", "4", "5" and "cool", and you want to pop off the "cool" element. You would use this snippet of code:

 $sample = array(1, 2, 3, 4, 5, "cool"); $last = array_pop($sample); 

You can use the example script below to print the "Before" and "After" versions of the $sample array and the value of $last:

 <?php $sample = array(1, 2, 3, 4, 5, "cool"); echo "BEFORE:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } reset($sample); $last = array_pop($sample); echo "<br>AFTER:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } echo "<br>and finally, in \$last: $last"; ?> 

The script will print the following:

  • BEFORE:

    0:1

    1:2

    2:3

    3:4

    4:5

    5 : cool

  • AFTER:

    0:1

    1:2

    2:3

    3:4

    4:5

and finally, in $last:cool

array_unshift()

The array_unshift() function allows you to add elements to the beginning of an existing array.

The syntax of the array_unshift() function is:

 array_unshift($array_name, "element 1", "element 2", ...); 

For example, say you have an array that contains the elements "1" and "2", and you want to add the elements "3", "4", "5", and "cool". You would use this snippet of code:

 $sample = array(1, 2); array_unshift($sample, 3, 4, 5, "cool"); 

You can use the example script below to print the "Before" and "After" versions of the $sample array:

 <?php $sample = array(1, 2); echo "BEFORE:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } reset($sample); array_unshift($sample, 3, 4, 5, "cool"); echo "<br>AFTER:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } ?> 

The script will print the following:

  • BEFORE:

    0:1

    1:2

  • AFTER:

    0:3

    1:4

    2:5

    3:cool

    4:1

    5:2

array_shift()

The array_shift() function allows you to take off the first element (shift the list back a step) of an existing array.

The syntax of the array_shift() function is:

 array_shift($array_name): 

For example, say you have an array that contains the elements "1", "2", "3", "4", "5", and "cool", and you want to pop off the "1" element. You would use this snippet of code:

 $sample = array(1, 2, 3, 4, 5, "cool"); $first = array_shift($sample); 

You can use the example script below to print the "Before" and "After" versions of the $sample array and the value of $first:

 <?php $sample = array(1, 2, 3, 4, 5, "cool"); echo "BEFORE:<br>"; while (list($key, $value) = each($sample)) {           echo "$key : $value<br>"; } reset($sample); $first = array_shift($sample); echo "<br>AFTER:<br>"; echo "in \$first: $first<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } ?> 

The script will print:

  • BEFORE:

    0:1

    1:2

    2:3

    3:4

    4:5

    5:cool

  • AFTER:

    in $first: 1

    0:2

    1:3

    2:4

    3:5

    4:cool

array_slice()

The array_slice() function allows you extract a chunk of an existing array.

The syntax of the array_slice() function is

 array_slice($array_name, start_position, offset, length); 

For example, say you have an array that contains the elements "1", "2", "3", "4", "5" and "cool", and you want to extract some portions of this array. Some examples are

 $sample = array(1, 2, 3, 4, 5, "cool"); // start at 2nd position $slicel = array_slice($sample, 1); // start at 2nd position, go to next to last $slice2 = array_slice($sample, 1, -1); // start 5th position $slice3 = array_slice($sample, 4); // start at 1st position,  take 3 elements $slice4 = array_slice($sample, 0, 3); 

You can use the example script below to print the "Before" version of the $sample array and the value of the various "slices":

 <?php $sample = array(1, 2, 3, 4, 5, "cool"); echo "BEFORE:<br>"; while (list($key, $value) = each($sample)) {           echo "$key : $value<br>"; } reset($sample); $slice1 = array_slice($sample, 1); $slice2 = array_slice($sample, 1, -1); $slice3 = array_slice($sample, 4); $slice4 = array_slice($sample, 0, 3); echo "<br>slice1 (start at 2nd position) looks like:<br>"; while (list($key, $value) = each($slice1)) {           echo "$key : $value<br>"; } echo "<br>slice2 (start at 2nd pos, go to next to last) looks like:<br>"; while (list($key, $value) = each($slice2)) {           echo "$key : $value<br>"; } echo "<br>slice3 (start 5th pos) at looks like:<br>"; while (list($key, $value) = each($slice3)) {           echo "$key : $value<br>"; } echo "<br>slice4 (start at 1st pos, print 3 elements) looks like:<br>"; while (list($key, $value) = each($slice4)) {           echo "$key : $value<br>"; } ?> 

The script will print each of the slices in succession.

array_merge()

The array_merge() function allows you to combine two or more existing arrays.

The syntax of the array_merge() function is:

 array_merge($array1, $array2, ...); 

For example, say you have an array that contains the elements "1", "2", "3", "4", "5", and "cool", and another array that contains the elements "a", "b", "c", "d", "e", and "cooler", and you want to combine the two. You would use this snippet of code:

 $sample1 = array(1, 2, 3, 4, 5, "cool"); $sample2 = array(a, b, c, d, e, "cooler"); $merged = array_merge($sample1, $sample2); 

You can use the example script below to print the "Before" and "After" versions of the arrays:

 <?php $sample1 = array(1, 2, 3, 4, 5, "cool"); echo "BEFORE - SAMPLE1:<br>"; while (list($key,$value) = each($sample1)) {           echo "$key : $value<br>"; } reset($sample1); $sample2 = array(a, b, c, d, e, "cooler"); echo "<br>BEFORE - SAMPLE2:<br>"; while (list($key,$value) = each($sample2)) {           echo "$key : $value<br>"; } reset($sample2); $merged = array_merge($sample1, $sample2); echo "<br>AFTER:<br>"; while (list($key,$value) = each($merged)) {           echo "$key : $value<br>"; } ?> 

The script will print each sample array.

array_keys()

The array_keys() function will return an array of all the key names in an existing array.

The syntax of the array_keys() function is

 array_keys($array_name); 

Suppose you have an array that looks like this:

 $sample = array("key0" => "1", "key1" => "2", "key2" => "3", "key3" => "4", "key4" => "5", "key6" => "cool"); 

You can use the example script below to print all the keys in $sample:

 <?php $sample = array("key0" => "1", "key1" =>  "2", "key2" => "3", "key3" => "4", "key4" => "5", "key6" => "cool"); echo "SAMPLE ARRAY:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } $keys = array_keys($sample); echo "<br>KEYS IN SAMPLE ARRAY:<br>"; while (list($key,$value) = each($keys)) {           echo "$key : $value<br>"; } ?> 

The script will print the following:

  • SAMPLE ARRAY:

    key0: 1

    keyl : 2

    key2 : 3

    key3 : 4

    key4 : 5

    key6 : cool

  • KEYS IN SAMPLE ARRAY:

    0 : key0

    1 : keyl

    2 : key2

    3 : key3

    4 : key4

    5 : key6

array_values()

The array_values() function will return an array of all the values in an existing array.

The syntax of the array_values() function is

 array_values($array_name); 

Suppose you have an array that looks like this:

 $sample = array("key0" => "1", "key1" => "2", "key2" => "3", "key3" => "4", "key4" => "5", "key6" =>  "cool"); 

You can use the example script below to print all the values in $sample:

 <?php $sample = array("key0" => "1", "key1" => "2", "key2" => "3", "key3" => "4", "key4" => "5", "key6" => "cool"); echo "SAMPLE ARRAY:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } $values = array_values($sample); echo "<br>VALUES IN SAMPLE ARRAY:<br>"; while (list($key,$value) = each($values)) {           echo "$key : $value<br>"; } ?> 

The script will print the following:

  • SAMPLE ARRAY:

    key0 : 1

    keyl : 2

    key2 : 3

    key3 : 4

    key4 : 5

    key6 : cool

  • VALUES IN SAMPLE ARRAY:

    0:1

    1:2

    2:3

    3:4

    4:5

    5 : cool

count()

The count() function counts the number of elements in a variable. It's usually used to count the number of elements in an array, because any variable that is not an array will have 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.

You can create a for loop that will loop through an array and print its elements, using the result of the count() function as the second expression in the loop. For example:

 $colors = array("blue", "black", "red", "green"): for ($i = 0; $i < count($colors); $i++) {           echo "The current color is $colors[$i].<br>"; } 

produces this result:

  • The current color is blue.

  • The current color is black.

  • The current color is red.

  • The current color is green.

In this example, the value of the count() function is used as the stopping point for the loop; the statement $i < count($colors) in this case is the equivalent of $i < 4.

each() and list()

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:

 while (list($key, $val) = each($HTTP_GET_VARS)) {           echo "$key has a value of $val<br>"; } 

Continuing the example, this would produce the following results:

  • first_name has a value of Joe.

  • last_name has a value of Smith.

reset()

The reset() function rewinds the pointer to the beginning of the array. The syntax of the reset() function is

 reset($array_name); 

shuffle()

The shuffle() function will randomize the elements of a given array. The syntax of the shuffle() function is

 shuffle($array_name); 

For example, say you have an array that contains the numbers "1" through "10" and you want to randomize the elements. You can use the example script below to print the "Before" and "After" versions of the $sample array:

 <?php $sample = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); echo "BEFORE:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } reset($sample); srand(time()); shuffle($sample); echo "<br>AFTER:<br>"; while (list($key,$value) = each($sample)) {           echo "$key : $value<br>"; } ?> 

The script will print the original, and then a randomly shuffled result.

sizeof()

The sizeof() function counts the number of elements in an array. In the following example, $a is assigned a value equal to the number of elements in the $colors array:

 $a = sizeof($colors); 

If $colors contains the values "blue", "black", "red", and "green", $a is assigned a value of 4.

You can create a for loop that will loop through an array and print its elements, using the sizeof() function as the second expression in the loop. For example:

 $colors = array("blue", "black", "red", "green"); for ($i = 0; $i < sizeof($colors); $i++) {           echo "The current color is $colors[$i].<br>"; } 

Here is the result:

  • The current color is blue.

  • The current color is black.

  • The current color is red.

  • The current color is green.

In this example, the value of the sizeof() function is used as the stopping point for the loop. The statement $i < sizeof($colors) in this case is the equivalent of $i < 4.

Database Connectivity Functions

Database connectivity functions in PHP tend to follow the same patterns: connect to database, get results, close connection, and so on. However, several specific database types have their own set of functions, taking into consideration the nuances of the software. The following sections show the basic syntax of the database functions for select database types. Extended examples for select database can be found in Chapter 3, "Working with Databases." Additional information on the multitude of other database connectivity functions can be found in the PHP Manual, at http://www.php.net/manual/.

MySQL Functions

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/ref.mysql.php for a complete listing of MySQL functions.

mysql_connect()

This function opens a connection to MySQL. It requires a server name, username, and password.

 $connection = mysql_connect("servername", "username","password"); 

mysql_select_db()

This function selects a database on the MySQL server for use by subsequent queries; it requires that a valid connection has been established.

 $db = mysql_select_db("myDB", $connection); 

mysql_query()

This function issues the SQL statement. It requires an open connection to the database.

 $sql_result = mysql_query("SELECT * FROM SOMETABLE",$connection); 

mysql_fetch_array()

This function automatically places the SQL statement result row into an array.

 $row = mysql_fetch_array($sql_result) 

mysql_free_result()

This function frees the memory resources used by a database query.

 mysql_free_result($sql_result); 

mysql_close()

This function explicitly closes a database connection.

 mysql_close($connection); 

PostgreSQL Functions

Numerous PHP functions exist for connecting to and querying a PostgreSQL Server. Following are some basic functions and their syntax. See the PHP Manual at http://www.php.net/manual/ref.pgsql.php for a complete listing of PostgreSQL functions.

pg_connect()

this function opens a connection to a PostgreSQL database; it requires a hostname, database name, username, and password.

 $connection = pg_connect("host=YourHostname dbname=YourDBName user=YourUsername password=YourPassword"); 

pg_exec()

This function issues the SQL statement; it requires an open connection to the database.

 $sql_result = pg_exec($connection,$sql); 

pg_fetch_array()

This function automatically places the SQL statement result row into an array.

 $row = pg_fetch_array($sql_result) 

pg_freeresult()

This function frees the memory resources used by a database query.

 pg_freeresult($sql_result); 

pg_close()

This function explicitly closes a database connection.

 pg_close($connection); 

Oracle Functions

Numerous PHP functions exist for connecting to and querying an Oracle version 7, 8, or 9 database server. Following are some basic functions and their syntax. See the PHP Manual at http://www.php.net/manual/ref.oci8.php for a complete listing of Oracle functions.

OCILogon()

This function opens a connection to Oracle; it requires that the environment variable ORACLE_SID has been set and that you have a valid username and password.

 $connection = OCILogon("username","password"); 

OCIParse()

This function parses a SQL statement; it requires an open database connection.

 $sql_statement = OCIParse($connection,"SELECT * FROM TABLENAME"); 

OCIExecute()

This function executes a prepared SQL statement.

 OCIExecute($sql_statement); 

OCIFetch()

This function gets the next row in the result of a SQL statement and places it in a results buffer; it requires a valid result set.

 OCIFetch($sql_statement); 

OCIResult()

This function gets the value of the named column in the current result row; it requires a valid result set.

 OCIResult($sql_statement,"COLUMN") 

OCIFreeStatement()

This function frees the resources in use by the current statement.

 OCIFreeStatement($sql_result); 

OCILogoff()

This function explicitly closes a database connection.

 OCILogoff($connection); 

Microsoft SQL Server Functions

There are numerous PHP functions for connecting to and querying Microsoft SQL Server. Following are some basic functions and their syntax. See the PHP Manual at http://www.php.net/manual/ref.mssql.php for a complete listing of Microsoft SQL Server functions.

mssql_connect()

This function opens a connection to the Microsoft SQL Server; it requires a server name, username, and password.

 $connection = mssql_connect("servername","username","password"); 

mssql_select_db()

This function selects a database on the Microsoft SQL Server for use by subsequent queries; it requires that a valid connection has been established.

 $db = mssql_select_db("myDB", $connection); 

mssql_query()

This function issues the SQL statement; it requires an open connection to the database.

 $sql_result = mssql_query("SELECT * FROM SOMETABLE",$connection); 

mssql_fetch_array()

This function automatically places the SQL statement result row into an array.

 $row = mssql_fetch_array($sql_result) 

mssql_free_result()

This function frees the memory resources used by a database query.

 mssql_free_result($sql_result); 

mssql_close()

This function explicitly closes a database connection.

 mssql_close($connection); 

ODBC Functions

PHP contains functions for making generic ODBC connections should your database type not have an explicit set of functions, or if you simply need to use ODBC connectivity. Following are some basic functions and their syntax. See the PHP Manual at http://www.php.net/manual/ref.odbc.php for a complete listing of ODBC functions.

odbc_connect()

This function opens an ODBC connection; it requires a server name, username, and password.

 $connection = odbc_connect("DSN=YourDataSourceName","username","password"); 

odbc_prepare()

This function readies a SQL statement for execution by the ODBC datasource.

 $sql_statement = odbc_prepare($connection,"SELECT * FROM TABLENAME"); 

odbc_execute()

This function executes a prepared SQL statement.

 $sql_result = odbc_execute($sql_statement); 

odbc_result_all()

This function automatically formats query results into an HTML table; it requires a query result and can optionally include HTML table attributes.

 odbc_result_all($sql_result,"border=1"); 

odbc_free_result()

This function frees the memory resources used by a database query.

 odbc_free_result($sql_result); 

odbc_close()

This function explicitly closes a database connection.

 odbc_close($connection); 

Date and Time Functions

The basic PHP date and time functions let you easily format timestamps for use in database queries and calendar functions, as well as simply printing the date on an order form receipt.

date()

The date() function returns the current server timestamp, formatted according to a given a set of parameters. Here is the syntax of the date() function:

 date(format, [timestamp]); 

If the timestamp parameter is not provided, the current timestamp is assumed. Table A.6 shows the available formats.

Table A.6: date() Function Formats

Character

Meaning

a

Prints "am" or "pm"

A

Prints "AM" or "PM"

h

Hour, 12-hour format (01 to 12)

H

Hour, 24-hour format (00 to 23)

g

Hour, 12-hour format without leading zero (1 to 12)

G

Hour, 24-hour format without 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 month, two digits (01 to 31)

j

Day of month, two digits without leading zero (1 to 31)

D

Day of week, text (Mon to Sun)

1

Day of week, long text (Monday to Sunday)

w

Day of week, numeric, Sunday to Saturday (0 to 6)

F

Month, long text (January to December)

m

Month, two digits (01 to 12)

n

Month, two digits without leading zero (1 to 12)

M

Month, three-letter text (Jan to Dec)

Y

Year, four digits (2000)

y

Year, 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)

For example, the following:

 echo date ("F jS Y, h:iA."); 

will print the current date in this format: December 16th 2002, 09:17AM.

checkdate()

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 are in each month (leap years are accounted for). Here's the syntax of checkdate():

 checkdate(month, day, year); 

For example, if you have a date such as "12/30/1973" (which happens to be my birthday so I'm pretty sure it's valid), you can use the following code to break apart the date and validate it, returning a response to the user:

 <?php $orig_date = "12/30/1973"; $date = explode("/", "$orig_date"); $month = $date[0]; $day = $date[1]; $year = $date[2]; $res = checkdate($month, $day, $year); if ($res == 1) {           echo "$orig_date is a valid date!"; } else {           echo "$orig_date is not valid."; } ?> 

The output of this script is

  • 12/30/1973 is a valid date!

mktime()

The mktime() function returns the UNIX timestamp as a long integer (in the format of seconds since the Epoch, which is 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. Here's the syntax of mktime():

 mktime(hour, minute, second, month, day, year); 

For example, if the month is December (12), the day of the month is 17, and the year is 2002:

 echo mktime(0, 0, 0, 12, 17, 2002); the result is 1040112000. 

time() and microtime()

The time() function returns the current system time, measured in seconds since the Epoch. The syntax of time() is simply

 time(); 

For example, to print the current system timestamp, use

 echo time(); 

You could get a result such as 1040112000. Well, actually you couldn't, because that moment has already passed, about 15 seconds before I wrote this sentence!

Using microtime() adds a count of microseconds, so instead of just 1040112000, I got 0.10026200 1040221299 at the exact moment I asked for the time since the Epoch, in both seconds and microseconds.

Filesystem Functions

The built-in filesystem functions can be very powerful tools—or weapons, if used incorrectly. Be very careful when using filesystem 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 would be a very bad thing.

chmod(), chgrp() and chown()

Like the shell commands of the same name, the chmod(), chgrp(), and chown() functions will modify the permissions, group, and owner of a directory or file. The syntax of these functions is

 chmod("filename", mode); chmgrp("filename", newgroup); chown("filename", newowner); 

For example, to change the permissions on a file called index.html in your home directory, use

 chmod("/home/username/index.html", 0755); 

To change to a new group, called users:

 chmgrp("/home/username/index.html", users); 

To change to a new owner, called joe:

 chown("/home/username/index.html", joe); 

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.

copy()

The copy () function works much like the cp shell command: it needs a file name and a destination in order to copy a file. The syntax of copy() is

 copy("source filename", "destination"); 

For example, to make a backup copy of the file index.html in your home directory, use

 copy("/home/username/index.html", "/home/username/index.html.bak"); 

The PHP user must have permission to write into the destination directory, or the copy function will fail.

diskfreespace()

The diskfreespace() function returns the total free space for a given directory, in bytes. The syntax of diskfreespace() is

 diskfreespace(directory); 

For example, to see the available space on your UNIX machine, use

 $space = diskfreespace("/"); echo "$space"; 

On your Windows machine, you can use

 $space = diskfreespace("C:\\"); echo "$space"; 

fopen()

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 file name string.

If the file name begins with anything else, then the file is opened from the filesystem and a file pointer to the opened file is returned. Otherwise, the file is assumed to reside on the local filesystem.

The specified mode determines whether the file is opened for reading, writing, or both. Table A.7 lists the valid modes.

Table A.7: fopen() Function 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.

For example, to open the file index.html in your home directory for reading only, use

 $fp = fopen("/home/username/index.html", "r"); 

To open a nonexistent file called temp.txt in your home directory, use

 $fp = fopen("/home/username/temp.txt", "w+"); 

fread()

Use the fread() function to read a specified number of bytes from an open file pointer. The syntax of fread() is

 fread(filepointer, length); 

For example, to read the first 1024 bytes of a file and assign the string as a value of a variable called $content, use this code:

 $fp = fopen("/home/username/temp.txt", "r"); // open the file pointer $content = fread($fp, 1024); // read 1024 bytes into a variable 

fputs()

The fputs() function writes to an open file pointer. The syntax of fputs() 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, then all specified content is written to the file.

For example, to write "I love PHP" to an open file pointer, use

 fputs($filepointer, "I love PHP"); 

Alternatively, you can place the content in a variable and then reference only the variable:

 $content = "I love PHP"; fputs($filepointer, $content); 

fclose()

Use the fclose() function to close an open file pointer. The syntax of fclose() is

 fclose(filepointer); 

For example, if you used the fopen() function to open a file pointer called $new_file, you would use the following code to close the file pointer:

 fclose($new_file); 

file_exists()

The file_exists() function checks to see if a file of the specified name already exists. The syntax of file_exists() is

 file_exists("filename"); 

For example, the following code checks to see if the file index.html exists in a directory and then prints a message depending on the results:

 if (!file_exists("/home/username/index.html")) {           echo "The file index.html does not exist."; } else {           echo "Success! index.html exists."; } 

mkdir()

Like the mkdir shell command, the mkdir() function creates a new directory on the filesystem. The syntax of mkdir() is

 mkdir("pathname", mode); 

For example, to create a directory called public_html in your home directory, use

 mkdir("/home/username/public_html", 0755); 

The PHP user must have write permission in the specified directory.

rename()

As its name suggests, the rename() function attempts to give a new name to an existing file. The syntax of rename() is

 rename("oldname", "newname"); 

For example, to rename a file in your home directory from index.html to temp1.html, use

 rename("/home/username/index.html", "/home/username/temp1.html"); 

The PHP user must have permission to modify the file.

rmdir()

Like the rmdir shell command, the rmdir() function removes a directory from the filesystem. The syntax of rmdir() is

 rmdir("pathname"); 

For example, to remove the directory public_html from your home directory, use

 rmdir("/home/username/public_html"); 

The PHP user must have write permission in the specified directory.

symlink()

The symlink() function creates a symbolic link from an existing file or directory on the filesystem to a specified link name. The syntax of symlink() is

 symlink("targetname", "linkname"); 

For example, to create a symbolic link called index.phtml to an existing file called index.html, use

 symlink("index.html", "index.phtml"); 

unlink()

The unlink() function deletes a file from the filesystem. The syntax of unlink() is

 unlink("filename"); 

For example, to delete a file called index.html in your home directory, use

 unlink("/home/username/index.html"); 

The PHP user must have write permission for this file.

HTTP Functions

The built-in functions for sending specific HTTP headers and cookie data are crucial to developing large Web-based applications in PHP. Luckily, the syntax for these functions is quite easy to understand and implement.

header()

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 over and over again: 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 new line 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. Doing so ensures that the code does not continue to execute.

setcookie()

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 test-company.com domain:

 setcookie("username","joe", time()+3600, "/", ".testcompany.com"); 

Mail Function

The PHP mail function makes the interface between your HTML forms and your server's mail program a snap!

mail()

If your server has access to sendmail or an external SMTP server, you can use the mail() function to send 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: youre- mail@yourdomain.com\n"); 

Mathematical Functions

As I have very little aptitude for mathematics, I find PHP's built-in mathematical functions to be of utmost importance! In addition to all the functions, the value of pi (calculated as 3.14159265358979323846) is already defined as a constant in PHP (M_PI).

ceil()

The ceil() function rounds a fraction up to the next higher integer. The syntax of ceil() is

 ceil(number); 

For example:

 ceil(2.56); // result is "3"; ceil(1.22); // result is "2"; 

decbin() and bindec()

The decbin() and bindec() functions convert decimal numbers to binary numbers and binary numbers to decimal numbers, respectively. The syntax of these functions is

 decbin(number); bindec(number); 

For example, the following code takes a decimal number, converts it to binary, and converts it back to decimal:

 <?php $orig_dec = 66251125; $dec2bin = decbin($orig_dec); $bin2dec = bindec($dec2bin); echo "original decimal number: $orig_dec <br>"; echo "new binary number: $dec2bin <br>"; echo "back to decimal: $bin2dec <br>"; ?> 

The output of this script is

  • original decimal number: 66251125

  • new binary number: 11111100101110100101110101

  • back to decimal: 66251125

dechex() and hexdec()

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); 

For example, the following code takes a decimal number, converts it to hexadecimal, and converts it back to decimal:

 <?php $orig_dec = 255; $dec2hex = dechex($orig_dec); $hex2dec = hexdec($dec2hex); echo "original decimal number: $orig_dec <br>"; echo "new hexadecimal number: $dec2hex <br>"; echo "back to decimal: $hex2dec <br>"; ?> 

The output of this script is

  • original decimal number: 255

  • new hexadecimal number: ff

  • back to decimal: 255

decoct() and octdec()

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); 

For example, the following code takes a decimal number, converts it to octal, and converts it back to decimal:

 <?php $orig_dec = 34672; $dec2oct = decoct($orig_dec); $oct2dec = octdec($dec2oct); echo "original decimal number: $orig_dec <br>"; echo "new octal number: $dec2oct <br>"; echo "back to decimal: $oct2dec <br>"; ?> 

The output of this script is

  • original decimal number: 34672

  • new octal number: 103560

  • back to decimal: 34672

floor()

The floor() function rounds a fraction down to the next-lowest integer. The syntax of floor() is

 floor(number); 

For example:

 floor(2.56); // result is "2"; floor(1.22); // result is "1"; 

number_format()

The number_format() function returns the formatted version of a specified number. The syntax of number_format() 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 has a comma between every group of thousands.

pow()

The pow() function returns the value of a given number, raised to the power of a given exponent. The syntax of pow() is

 pow(number, exponent); 

For example, this code raises 19 to the fifth power:

 echo pow(19, 5); 

The result is 2476099.

rand()

The rand() function generates a random value from a specific range of numbers. The syntax of rand() is

 rand(min, max); 

For example, to return a random value between 0 and 576, use

 echo rand(0,576); 

round()

The round() function rounds a fraction to the next higher or next lower integer. The syntax of the round() function is

 round(number); 

For example:

 round(2.56);       // returns "3" round(1.22);       // returns "1" round(55.22);      // returns "55" 

sqrt()

The sqrt() function returns the square root of a given number. The syntax of sqrt() is

 sqrt(number); 

For example, to find the square root of 5561, use

 echo sqrt(5561); 

The result is 74.572112750009.

srand()

The srand() function provides the random number generator with a set of possible values. The syntax of srand() is

 srand(seed); 

A common practice is to seed the random number generator by using a number of microseconds:

 srand ((double)microtime()*1000000); 

Miscellaneous Functions

The die() and exit functions provide useful control over the execution of your script, offering an "escape route" for programming errors.

die()

The die() function outputs a given message and terminates the script when a returned value is false. The syntax of die() 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."); 

exit

The exit function terminates the execution of the current script at the point where the exit function is called.

For example, to exit the script after a location redirection header has been sent, use

 header("Location: http://www.newlocation.com/"); exit; 

sleep() and usleep()

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.

uniqid()

The uniqid() function generates a unique identifier, with a prefix if you so desire. The basic syntax of uniqid() is

 uniqid("prefix"); 

That's boring, though. Suppose you want a unique id with a prefix of "phpuser", so you use

 $id = uniqid("phpuser"); echo "$id"; 

and get something like phpuser38b320a6b5482.

But if you use something really cool like

 $id - md5(uniqid(rand())); echo "$id"; 

Then you get an id like 999d8971461bedfc7caadcab33e65866.

Network Functions

There are several network functions available. Some are for opening and reading from sockets, and some are FTP functions. The two network functions that I use most often are the IP and name resolution functions.

gethostbyaddr() and gethostbyname()

The gethostbyaddr() and gethostbyname() functions will return the hostname or IP address of a given machine, respectively. The syntax of these commands is

 gethostbyaddr(IP); gethostbyname(hostname); 

The sample code below shows both of these functions in action:

 <?php // assign some variables Sip = "204.71.200.75"; $host = "www.yahoo.com"; $verify_ip = gethostbyaddr($ip); $verify_name = gethostbyname($host); echo "$ip resolves to $verify_ip<br>"; echo "$host resolves to $verify_name<br>"; ?> 

The output of this script is:

  • 204.71.200.75 resolves to www10.yahoo.com

  • www.yahoo.com resolves to 204.71.200.74

PHP Version and Related Information

Sometimes you'll need to get a quick snapshot of your operating environment, especially if you're like me and can't remember what you've loaded on which Web server! PHP has a few functions that make environment information very easy to discover and modify.

phpinfo()

Calling the phpinfo() function will output a template containing PHP version information, extensions information, and numerous other environment variables. Simply create a file with one line in it:

 <? phpinfo(); ?> 

Access that file with your Web browser. You'll see more information than you ever needed to know!

phpversion()

If phpinfo() provides more information than you want, you can use the phpversion() function to return just the version number currently in use. For example, on one of my systems, this snippet of code

 echo "Current version is: ".phpversion(); 

shows

  • Current version is: 4.0b3

Program Execution Functions

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.

exec()

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>"; } 

passthru()

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.

system()

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:

 $command = "ping -c5 www.thickbook.com"; system($command); 

Regular Expression Functions

Regular expressions are used during string manipulation and vary in complexity. PHP has several built-in functions that utilize a powerful, bundled regular expression library.

ereg_replace() and eregi_replace()

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

split()

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]); 

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 onto data as a user navigates your Web site. 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.

session_start()

The session_start() function starts a session if one has not already been started, or it resumes a session if the session ID is present for the user. This function takes no arguments and is called simply by placing the following at the beginning of your code:

 session_start(); 

session_destroy()

The session_destroy() function effectively destroys all the variables and values registered for the current session. This function takes no arguments and is called simply by placing the following in your code:

 session_destroy(); 

String Functions

This section will only scratch 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!

addslashes() and stripslashes()

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 the syntax

 addslashes(string); 

Similarly, the stripslashes() function will return a string with the slashes taken away, using the syntax

 stripslashes(string); 

chop(), ltrim() and trim()

All three of these functions remove errant white space from a string. The chop() function removes white space from the end of a string, while ltrim() removes white space from the beginning of a string. The trim() function removes both leading and trailing white space from a string. The syntax of these functions is

 chop(string); ltrim(string); trim(string); 

echo()

The echo() function returns output. The syntax of echo() is

 echo (parameter1, 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.

explode() and implode()

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, then creates a string called $mycolors, containing the values of the $color_list array, separated by commas:

 $mycolors = implode(",", $color_list); 

htmlspecialchars() and htmlentities()

The htmlspecialchars() and html entities() functions convert special characters and HTML entities within strings into their acceptable entity representations. The htmlspecialchars() function only converts the less-than sign (< becomes &lt;), greater-than sign (> becomes &gt;), double quotes ("" becomes &quot;) and the ampersand (& becomes &amp;). The htmlentities() function will convert the characters in the ISO-8859-1 character set to the proper HTML entity. The syntax of these functions is

 htmlspecialchars(string); htmlentities(string); 

nl2br()

The nl2br() function will replace all ASCII newlines with the XHTML-compliant line break (<BR/>). The syntax of the nl2br() function is

 nl2br(string); 

sprintf()

The sprintf() function returns a string that has been formatted according to a set of directives. The syntax of sprintf() is

 sprintf(directives, string); 

Table A.8 lists the formatting directives.

Table A.8: sprintf() Function Formatting Directives

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).

For example, to format currency using sprintf(), use this code:

 <? $tax = 1.06; $subtotal = 10.94; $total = $tax + $subtotal; $fmt_total = sprintf ("%0.2f", $total); echo "$fmt_total"; ?> 

The value of $fmt_total is 12.00 instead of simply 12.

strlen()

The strlen() function returns the length of a given string. The syntax of the strlen() function is

 strlen(string); 

strtolower()

The strtolower() function returns a given string with all alphabetic characters in lowercase. The syntax of strtolower() is

 strtolower(str); 

For example, to return ABGH 10023 as lowercase, use

 echo strtolower("ABGH 10023"); 

The result is abgh 10023.

strtoupper()

The strtoupper() function returns a given string with all alphabetic characters in uppercase. The syntax of strtoupper() is

 strtoupper (str); 

For example, to return abgh 10023 as uppercase, use

 <? echo strtoupper ("abgh 10023"); ?> 

The result is ABGH 10023.

substr()

The substr() function returns a portion of a string, given a starting position and optional ultimate length. The syntax of substr() 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, then 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:

 <? $new_string = substr("PHP is great!", 1); // returns "HP is great!" $new_string = substr("PHP is great!", 0, 7); // returns "PHP is" $new_string = substr("PHP is great!", -1); // returns "!" $new_string = substr("PHP is great!", -6, 5); // returns "great" ?> 

ucfirst()

The ucfirst() function changes the first alphabetic character in a string to an uppercase character. The syntax of ucfirst() is

 ucfirst(string); 

For example, if your string is "i love PHP", the following code returns "I love PHP":

 ucfirst("i love PHP"); 

ucwords()

The ucwords () function changes the first letter of each word in a string to uppercase. The syntax of ucwords() is

 ucwords(string); 

For example, if your string is "i love PHP", the following code will return "I Love PHP":

 ucwords("i love PHP"); 

Variable Functions

The two basic variable functions, isset() and unset(), help you manage your variables within the scope of an application.

isset() and unset()

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. For example, if you have a variable called $foo with a value of "bar", the following returns true:

 $foo = "bar"; echo isset($foo); 

Now, if you use the unset() function on $foo, like this:

 unset($foo); 

The value of isset($foo) will now be false:

 echo isset($foo); // FALSE! 



PHP Essentials
PHP Essentials, 2nd Edition
ISBN: 1931841349
EAN: 2147483647
Year: 2002
Pages: 74

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net