Tuesday, August 11, 2009

Ten Things You Might Want to Do Using PHP Functions

ne of the strongest aspects of PHP is its many built-in functions. In this chapter, I list the PHP functions that I use most often. I describe some of
them elsewhere in this book, some I only mention in passing, and some I don’t mention at all. These aren’t all the functions, by any means. There are many hundreds of functions in the PHP language. For a complete list of all the func­ tions, see the PHP documentation at www.php.net.

Communicate with MySQL

PHP has many functions designed specifically for interacting with MySQL. I describe the following MySQL functions thoroughly in this book, particularly in Chapter 8:

mysql_connect(); mysql_select_db(); mysql_fetch_array()
mysql_close(); mysql_num_rows(); mysql_query()

The following functions could be useful, but I either don’t discuss them or discuss them only briefly in earlier chapters:

mysql_insert_id(): For use with an AUTO-INCREMENT MySQL column.
This function gets the last number inserted into the column.

mysql_fetch_row($result): Gets one row from the temporary results location. The row is put into an array with numbers as the keys. It’s the same as mysql_fetch_array($row,MYSQL_NUM).

mysql_affected_rows($result): Returns the number of rows that were affected by a query — for instance, the number of rows deleted or updated.

mysql_num_fields($result): Returns the number of fields in a result.

mysql_field_name($result, N): Returns the name of the row indi­ cated by N. For instance, mysql_field_name($result,1) returns the name of the second column in the result. The first column is 0.

If you use any of the above functions with MySQL 4.1, the function’s names are slightly different. Rather than beginning with mysql_, the function names begin with mysqli_.

Send E-Mail

PHP provides a function that sends e-mail from your PHP program. The format is

mail(address,subject,message,headers);

These are the values that you need to fill in:

address: The e-mail address that will receive the message.

subject: A string that goes on the subject line of the e-mail message.

message: The content that goes inside the e-mail message.

headers: A string that sets values for headers. For instance, you might have a headers string as follows:

“From: member-desk@petstore.com\r\nbcc: mom@hercompany.com”

The header would set the From header to the given e-mail address, plus send a blind copy of the e-mail message to mom.

The following is an example of PHP statements that you can use in your script to set up and send an e-mail message:

$to = “janet@valade.com”;
$subj = “Test”;
$mess = “This is a test of the mail function”;
$headers = bcc:techsupport@mycompany.com\r\n
$mailsend = mail($to,$subj,$mess,$headers);

Sometimes you might have a problem with your e-mail. PHP has a configura­ tion setting that must be correct before the mail function can connect to your system e-mail software. The default is usually correct, but if your e-mail doesn’t seem to be getting to its destination, check the PHP configuration
mail setting by looking for the following in the output of phpinfo():

Sendmail_path (on Unix/Linux) SMTP (on Windows)

It might be set incorrectly. You can change the setting by editing the php.ini
file. Look for the following lines:

[mail function]
; For Win32 only. SMTP = localhost

; For Win32 only.
sendmail_from = me@localhost.com

; For Unix only.
;sendmail_path =

Windows users need to change the first two settings. The first setting is where you put the name of your outgoing mail server. However you send
e-mail — LAN at work, a cable modem at home, an ISP via a modem — you send your mail with an SMTP server, which has an address that you need to know.

If you send directly from your computer, you should be able to find the name of the outgoing mail server that you’re using in your e-mail software. For instance, in Microsoft Outlook Express, choose Tools➪Accounts➪Properties and then select the Servers tab. Look for the name of your outgoing mail server. If you can’t find its name, you can ask your e-mail administrator for the name. If you use an ISP, you can ask the ISP. The name is likely to be in a format similar to the following:

mail.ispname.net

The second setting is the return address that is sent with all your e-mail. Change the setting to the e-mail address that you want to use for your return address, as follows:

sendmail_from = Janet@Valade.com

The third setting is for Unix users. The default is usually correct. If it doesn’t work, you need to talk to your system administrator about the correct path to your outgoing mail server. This usually refers to Linux as well.

Don’t forget to remove the semicolon at the beginning of the lines. The semi­ colon makes the line into a comment, so the setting isn’t active until you remove the semicolon.

Use PHP Sessions

The functions to open or close a session follow. I explain all these functions in Chapter 9.

session_start(); session_destroy()

Stop Your Program

Sometimes you just want your program to stop, cease, and desist. There are two functions for this: exit() and die(). Actually, these are two different names for the same function. Exit is probably accurate, but sometimes it’s just more fun to say die. Both functions will print a message when they stop if you provide one. The format is

exit(“message string”);

When exit executes, the message string is output.

Handle Arrays

Arrays are very useful in PHP, particularly for getting the results from data­ base functions and for form variables. I explain the following array functions elsewhere in the book, mainly in Chapter 7:

array(); extract(); sort(); asort();
rsort(); arsort(); ksort(); krsort();

Here are some other useful functions:

array_reverse($varname): Returns an array with the values in reverse order.

array_unique($varname): Removes duplicate values from an array.

in_array(“string”,$varname): Looks through an array $varname for a string “string”.

range(value1,value2): Creates an array containing all the values between value1 and value2. For instance, range(‘a’,’z’) creates an array containing all the letters between a and z.

explode(“sep”,”string”): Creates an array of strings in which each item is a substring of string, separated sep. For example, explode(“ “,$string) creates an array in which each word in
$string is a separate value. This is similar to the split function in Perl.

implode(“glue”,$array): Creates a string containing all the values in
$array with glue between them. For instance, implode(“, “,$array) creates a string: value1, value2, value3, and so on. This is similar to the join function in Perl.

And there are many more useful array functions. PHP can do almost anything you can think of that you want to do with an array.

Check for Variables

Sometimes you just need to know whether a variable exists. The following functions can be used to test whether a variable is currently set:

isset($varname); // true if variable is set
!isset($varname); // true if variable is not set empty($varname); // true if value is 0 or is not set

Format Values

Sometimes you need to format the values in variables. In Chapter 6, I explain how to format numbers into dollar format by using number_format() and sprintf(). In Chapter 6, I also discuss unset(), which removes the values from a variable. In this section, I describe additional capabilities of sprintf().

The function sprintf() allows you to format any string or number, including variable values. The general format is

$newvar = sprintf(“format”,$varname1,$varname2,...);

where format gives instructions for the format and $varname contains the value(s) to be formatted. format can contain both literals and instructions for formatting the values in the $varname. Actually, the format can contain only literals. The following statement is valid:

$newvar = sprintf(“I have a pet”);

This statement outputs the literal string. However, you can also add vari­
ables, using the following statements:

$ndogs = 5;
$ncats = 2;
$newvar = sprintf(“I have %s dogs and %s cats”,$ndogs,$ncats);

The %s is a formatting instruction that tells sprintf to insert the variable value as a string. Thus, the output is I have 5 dogs and 2 cats. The % character signals sprintf that a formatting instruction starts here. The for­ matting instruction has the following format:

%pad-width.dectype

These are the components of the formatting instructions:

%: Signals the start of the formatting instruction.

pad: A padding character that’s used to fill out the number when neces­ sary. If you don’t specify a character, a space is used. pad can be a space, a 0, or any character preceded by a single quote (‘). For instance, it’s common to pad numbers with 0 — for example, 01 or 0001.

-: A symbol meaning to left-justify the characters. If this isn’t included, the characters are right-justified.

width: The number of characters to use for the value. If the value doesn’t fill the width, the padding character is used to pad the value. For instance, if the width is 5, the padding character is 0, and the value is 1, the output is 00001.

.dec: The number of decimal places to use for a number.

type: The type of value. Use s for most values. Use f for numbers that you want to format with decimal places.

Some possible sprintf statements are

sprintf(“I have $%03.2f. Does %s have any?”,$money,$name);
sprintf(“%’.-20s%3.2f”,$product,$price);

The output of these statements is

I have $030.00. Does Tom have any? Kitten.............. 30.00

Compare Strings to Patterns

In earlier chapters in this book, I use regular expressions as patterns to match strings. (I explain regular expressions in Chapter 6.) The following functions use regular expressions to find and sometimes replace patterns in strings:

ereg(“pattern”,$varname): Checks whether the pattern is found in
$varname. eregi is the same function except that it ignores upper- and lowercase.

ereg_replace(“pattern”,”string”,$varname): Searches for the pattern in $varname and replaces it with the string. eregi_replace is the same function except that it ignores upper- and lowercase.

Find Out about Strings

Sometimes you need to know things about a string, such as how long it is or whether the first character is an uppercase O. PHP offers many functions for checking out your strings:

strlen($varname): Returns the length of the string.

strpos(“string”,”substring”): Returns the position in string where substring begins. For instance, strpos(“hello”,”el”) returns 1. Remember that the first position for PHP is 0. strrpos() finds the last position in string where substring begins.

substr(“string”,n1,n2): Returns the substring from string that begins at n1 and is n2 characters long. For instance, substr(“hello”,2,2) returns ll.

strtr($varname,”str1”,”str2”): Searches through the string
$varname for str1 and replaces it with str2 every place that it’s found.

strrev($varname): Returns the string with the characters reversed.

Many, many more string functions exist. See the documentation at
www.php.net.

Change the Case of Strings

Changing uppercase letters to lowercase and vice versa is not so easy. Bless
PHP for providing functions to do this for you:

strtolower($varname): Changes any uppercase letters in the string to lowercase letters

strtoupper($varname): Changes any lowercase letters in the string to uppercase letters

ucfirst($varname): Changes the first letter in the string to uppercase

ucwords($varname): Changes the first letter of each word in the string to uppercase

0 comments: