Saturday, January 31, 2009

Email with PHP

One of the most common tasks that a PHP programmer has to tackle is the development of applications that send MIME email in one form or another. In simple terms, MIME email consists of an extension of traditional email technology and comes in handy for sending email messages in fancy HTML and handling file attachments in a wide variety of formats. This article is the first part of a five-part series.

While using MIME email with PHP is a pretty fun process, the bad news is that it can be quite challenging to implement, particularly if you're not very familiar with its most complex facets. There's also the possibility that you often find yourself writing the same annoying code over and over again, especially when you have to construct MIME email modules within your applications.

In either case, one thing is certain: creating MIME email-related scripts with PHP is one of those things that you'll only want to do once in your lifetime. Suppose you're sick of writing code used to send MIME email to your customers and wish to find a more practical solution to this task. Well, you could pick up one of the numerous third-party classes that are available on the web, or develop your own fine-tuned MIME email class that can be reused many times in the future.

If you have any interest in the last option, then you'll find this article series pretty useful. In the different tutorials that comprise it, I'll teach you how to build a modular MIME mailer class with PHP 5. It will be equipped with a bunch of intuitive methods that are useful for handling the most common tasks associated with sending MIME email.

In this first part of the series, I'll walk you through creating the bare bones structure of the mailer class, and I'll be progressively adding more to it in upcoming articles.

Now, let's move forward and learn how to build a reusable MIME mailer class with PHP. Here we go!

php with forms

PHP forms with examples

PHP is one of the most popular means of processing HTML forms. This website will show you how to process PHP form and send form results to your e-mail address.

» Process PHP forms the secure way!

This tutorial has emphasis on processing PHP forms with security in mind! There are too many tutorials out there that rely on PHP's notorious register_globals setting activated with very little or no form input validating. Proper validation of form input data is the most important step in protecting your form from hackers and spammers!

This php form tutorial is sponsored by GWdish.com Dish Network

» Is this tutorial for me?

If you have at least basic understanding of HTML and PHP you shouldn't have any problems with this tutorial. You will not learn HTML here and this is also not a complete PHP tutorial, but rather a tutorial on working with HTML forms in PHP.

» PHP forms tutorial

The first part of this website is a tutorial about handling HTML forms with PHP. We recommend starting with the first lesson and reading through others. Each ensuing lesson will assume you already have knowledge from the previous one. Also the same code is used and upgraded throughout the tutorial.
1.1 PHP forms tutorial <- START HERE
1.2 Validating forms with PHP
1.3 Required and optional fields
1.4 Validating URL and E-mail
1.5 Form to mail
1.6 Putting it all together
1.7 Final words and further reading


» PHP forms "How to"

The "How to" section consists of articles and code examples covering some specific issues, requirements and features of PHP forms.

If you are not familiar with PHP and handling HTML forms we recommend that you start with the above tutorial first before reading these articles.
2.1 PHP form not working
2.2 Sending form results to multiple recipients
2.3 Sending an autoresponder message
2.4 Make sure form e-mails are not blocked by your SPAM filter
2.5 Stop form SPAM without using Captcha
2.6 Which method to use for your form: GET or POST?
2.7 Contact forms or Help desk software?
2.8 Prevent multiple form submissions

Form to Mail Script

This PHP script will generate nicely formatted emails based on fields posted to the script from a form. The script is a lot more advanced than most of the PHP mail scripts that I have seen elsewhere on the web. This script can handle any formatting associated with emails with both HTML and plain text. It also handles attachments as well as embedding images directly into the HTML emails. The following information tells you how to check that the script will run on your server, how to configure it, and what it can do.
Will it run on my server?

To be able to use this script you should first Check the Server to ensure that your host supports PHP. Next, try creating a php page containing the following text and see if you receive an email when you run the page (substitute your email address for you@your.email). If the email arrives (with subject of "test message" and content of "This is a test") then the script will work on your server.

Configuration

Configuring the form to mail script need be done only once when you first install it on your site.
Calling the script

Attaching the form to mail script to a form on your web page is relatively straightforward. You just need to be aware of those form fields that have a special meaning to the script.

If you want to see for yourself something of what can be done with this form to email script please enter your email address into the following form and send yourself a sample email using the script. The free version of the script is attached to the email and a link to the advanced version of the script is also included.
Examples

There are a number of examples of how to use this form to mail script which demonstrate how it can be used to create a variety of different types of emails from simple plain text ones to combinations of text and HTML with attachments and embedded images.
How to obtain the script

Unfortunately, I have to try to fund the running of this web site somehow and so I have decided to charge a nominal amount for server side scripts such as the more advanced version of this one. You can download the simpler version at no charge but you will be missing out on all of the advanced formatting functions as well as html, attachment and embedded image support.

Use the following form to purchase the Advanced version of the Felgall Form to eMail PHP script that can handle all of the customizations described above for just $10.80 USD (Australian residents price is $17.00 AUD including GST). All purchases include 12 months free support including all updates to the script released during that time. If you have a valid discount code then enter it to purchase this script at an even lower price otherwise just leave the discount field blank, select the currency to make your payment and then press the buy now button. The script will be automatically emailed to you as soon as Paypal verifies your payment.

Before you purchase this script you should reread the above information to ensure that the script will work on your server. You can also test that the free version of the script will work on your server before purchasing the advanced version. As much of the code is common between the two versions you can be sure that the advanced version that you purchase will work correctly if the free version does. If you cancel at any point during the payment process, you will be returned to this page.

Final notes

You should take into account that the configuration of your test server may differ from your web host configuration. Although most of the pages/scripts will run in the same way, some things can behave different or won't work at all.

For Apache, this problem is mainly an issue of having a different set of active modules than in your web host, and of course, this can be solved activating or deactivating that modules. Besides this, the configuration options of httpd.conf are mostly related to security and technical issues (like supporting subdomains, adding virtual folders...). Usually, the configuration relative to pages (URL rewriting, redirects...) is stored in .htaccess files.

For PHP the differences in the configuration are more relevant since they can modify how some scripts works (like the already mentioned register_globals option). The configuration set by the PHP installer includes the set of options recommended by PHP.net, which is used by most servers, but the final configuration is in the hands of the server administrator.

For example, an usual configuration change for production environments is suppressing the display of error messages that aren't critical, and thus limiting the information available to possible attackers. Although this change doesn't affect the behaviour of the scripts, you can be greeted with a lot of "E_NOTICE" errors the first time you run your scripts in your test server.

An related to MySQL, the main difference probably would be that in the test server you have full administrator rights while in your web host you won't have some of that rights. This shouldn't affect scripts, since in a properly configured server you should have all the rights needed for quering and managing your databases, and you can create an user with the same limitations of the one you have in your web server. Another difference is that you will have a different user & password in your web host, but you can replicate it in the test server.

Anyway, having a test server in your computer can speed up the development on your pages and scripts, and allows developing and testing server scripts even when you don't have an Internet connection available.

PHP Functions and keywords

associative array An array that uses text indexes; an associative array would be used as follows: $arrSomeArray[‘elementName’]

client-side scripting Script code that runs on the client machine (as opposed to the server machine). A common example of this is JavaScript code, which is executed by a user’s browser.

server-side scripting Scripting that is executed on the server before anything is sent to the client.

constructor A function that is called automatically upon a new instantiation of a class.

cookie A small piece of information that can be stored on a client machine by a program on the server if the browser allows it.

database A collection of data held in a specific place and usually accessed through a database server, such as MySQL.

global The main scope in a PHP script; all variables not contained in functions and classes.

here-doc A string-quoting style that allows for clearly readable multiline strings; most closely related to doubled quoting in PHP.

HTTP The protocol used by Web servers and browsers to request and transfer files.

inheritance The automatic gaining of a parent class’s member variables and functions.

JavaScript A scripting language unrelated to Java (with the exception of a few syntactical and structural similarities); almost always executed client-side.

object-oriented programming language A programming language, such as C++, Java, or PHP, that makes use of abstract data types (classes).

Object-Oriented Programming (OOP) Programming in an OO (objectoriented) language, which enables the programmer to model real-world concepts with classes and thus break problems down into smaller, independent or interdependent parts.

open source software Software to which the source code is freely available.

pattern matching The act of matching a regular expression against a string.

parent class The class from which a subclass was derived.

recursion The calling of a function from itself. The result is similar to a loop, but less efficient and generally more confusing.

reference An alias to a variable.

row A single record or entry in a MySQL table.

column A set of all the same fields from every row in a table.

regular expression A collection of special wildcard characters used to search strings for only partially known string patterns.

string A collection of one or more letters; a string can be a word, a sentence, or just a single letter.

subclass A class created by extending a parent class using the extends keyword.

type casting The act of forcing a variable to become a given type.

true The opposite of false. Can also be represented by any non-zero number, non-null value, or non-empty string.

unary operator An operator that only takes one argument. Example: the negative sign in –21 is a unary operator.

whitespace Any character that doesn’t print a visible character on the screen; whitespace characters include new lines (\n), spaces, tabs, and so on.

Array Functions:

array
Creates a new array.
Format: $array = array(key=>value, key=>value, key=>value,...);
array_count_values
Creates an array that contains a count of the values in the original array.
Format: $array_out = array_count_values($orig_array);
For example, suppose that $orig_array contained the following:
$orig_array[a] = John
$orig_array[b] = Mary
$orig_array[c] = John
$orig-Array[d] = Jose
Then $array_out would contain the following:
$array[John] = 2
$array[Mary} = 1
$array[Jose] = 1

array_diff
Returns $array_out with elements from $array1 that are not present in any other of the specified arrays ($array2, $array3, and so on).
Format: $array_out = array_diff($array1,$array2,$array3 . . .);
array_intersect
Creates an array that contains the elements that are the same (rather than different) in two or more arrays. Format: $simArray = array_intersect($array1,$array2, . . .);
array_keys
Creates an array containing all the keys in the $orig_array. If search_key is included, only keys that match search_key are in the new array.
Format: $array_out = array_keys($orig_array,”search_key”);
For example, suppose that $orig_array contained the following:
$orig_array[a] = CA
$orig_array[b] = OR
$orig_array[c] = TX
Then $array_out would contain the following:
$array_out[0] = a
$array_out[1] = b
$array_out[2] = c
Suppose that search_key= OR, as in the following:
$array_out = array_keys($orig_array,”OR”);
Then $array_out would contain the following:
$array_out[0] = b
array_merge
Merges two or more arrays together. If more than one element has the same non-numeric key, only the last value for the key is added to the output array.
Format: $bigArray = array_merge($array1,$array2, . . .);
array_merge_recursive
Merges two or more arrays. If more than one element has the same nonnumeric key, an array with all the values for the key is added to the output array.
Format: $bigArray = array_merge($array1,$array2, . . .);
array_pop --> Removes and returns the last element in an array.
Format: $element = array_pop($orig_array);
array_push
Adds the specified element(s) to the end of the array. Returns the new size of the array.
Format: $new_size = array_push($orig_array,”el1”,”el2”,”el3”);
array_reverse --> Reverses the order of the items in $orig_array.
array_search --> Searches an array for a value. If value is found, key is returned.
Format: $key = $array_search(“value”,$orig_array);
array_slice
Creates a new array that contains a subset of an existing array. Puts number of elements, beginning with start, into $subArray.
Format: $subArray = array_slice($orig_array,start,number);
array_sum --> Adds all the values in an array.
Format: $sum = array_sum($orig_array);
array_unique --> Removes duplicate elements from an array.
Format: $array_out = array_unique($orig_array);
arsort --> Sorts an array by value in reverse order.
Format: arsort($orig_array);
assort --> Sorts an array by value, keeping the original keys.
Format: asort($orig_array);
compact
Creates an array from the specified variables ($var1, $var2, and so on). The variables can be strings or arrays.
Format: $array_out = compact($var1, $var2, . . .);
Count --> Returns the number of elements in the array.
Format: $size = count($orig_array);
current --> Returns the value of the array element where the pointer is currently located.
Format: $value = current($array);
end --> Moves the pointer to the last element in an array and returns the value.
Format: $value = end($array);
explode
Creates an array containing substrings of a string. The specified separator, sep, which is generally something like a comma or a tab, divides the string into substrings.
Format: $array_out = explode(“sep”,$string);
extract
Creates a set of variables, one for each element of an array. The key for the element is used as the variable name.
Format: extract($array);
implode
Builds a string containing the values of all the elements in an array, separated by the specified separator.
Format: $string = implode($array,”sep”);
in_array
Searches through the values in an array for a specified value. Returns TRUE or FALSE.
Format: $bool = in_array(“value”,$array);
key --> Returns the key of the array element where the pointer is currently located.
Format: $key = key($array);
key_exists
Checks an array to see whether it contains an element with the specified key. Returns TRUE or FALSE.
Format: $bool = key_exists(“key”,$array);
ksort, krsort
Sorts the array by key. ksort sorts in ascending order, and krsort sorts in reverse (descending) order.
Format: ksort($array); krsort($array);
natsort, natcasesort
Sorts an array by value in natural order. The order of the results is n1, n2, n12, n25, rather than n1, n12, n2, n25 in the usual sort. The function natcasesort works the same way but is case-insensitive.
Format: natsort($array); natcasesort($array);
next --> Moves pointer in array to next element.
Format: next($array);
prev --> Moves pointer in array to previous element.
Format: prev($array);
range
Sets up an array with elements spanning a range of values. Possible ranges can be numerical (such as 1–10 or 10@nd1) or alphabetical (such as a–m or m–a).
Format: $array_out = range(start,end);
reset --> Moves pointer to the first element in an array.
Format: reset($array);
sizeof --> Returns the number of elements in an array.
Format: $size = sizeof($array);
sort, rsort
Sorts array by value. sort sorts in ascending order, and rsort sorts in reverse (descending) order.
Format: sort($array); rsort($array);
Format: $array_out = array_reverse($orig_array

Date and Time Functions

checkdate --> Checks whether date is valid. Returns TRUE or FALSE.
Format: checkdate(month,day,year);
date, gmdate
Converts a Unix timestamp into a formatted date. The function gmdate returns Greenwich Mean Time. Format: $formatted_date = date(“format”,$timestamp);
getdate
Creates an array from a Unix timestamp, each element containing part of the array, such as seconds, minutes, month, day of the year, and so on.
Format: $array_date = getdate($timestamp);
localtime
Creates an array of values related to your local time, such as seconds, minutes, day of month, and so on.
Format: $array_date = localtime($timestamp);
Microtime --> Returns time in seconds and microseconds since January 1, 1970.
Format: $time_out = microtime();
mktime, gmmktime --> Returns a Unix timestamp. gmmktime uses Greenwich Mean Time.
Format: $timestamp=mktime(“hrs”,”min”,”sec”,”mo”,”da”,”yr”);
time --> Returns the Unix timestamp for the current time.
Format: $timestamp = time();

File System Functions

basename --> Returns the filename from a full path.
Format: $filename = basename(“path”);
chdir --> Change to a different directory.
Format: chdir(“pathtodirectory”);
chgrp --> Changes the group for a file.
Format: chgrp(“pathtofile”,”group”);
chmod --> Changes the permissions of the file.
Format: chmod(“pathtofile”,”octalnumber”);
chown --> Changes the owner of a file.
Format: chown(“pathtofile”,”newowner”);
closedir --> Closes the directory pointed to by the directory handle $dh.
Format: closedir($dh);
copy --> Copies a file, resulting in two copies of the file.
Format: copy(“oldfilename”,”newfilename”);
dirname --> Returns the directory from a path.
Format: $directory_name = dirname(“path”);
dis_total_space --> Returns the number of bytes of total space on the disk.
Format: $space = disk_total_space(“path”);
disk_free_space --> Returns the number of bytes of free (unused) space.
Format: $free = disk_free_space(“pathtodir”);
fclose --> Closes an open file pointed to by the file handle $fh.
Format: fclose($fh);
feof --> Returns TRUE when the pointer reaches the end of the file.
Format: feof($fh);
fgetc
Returns one character (the current character) and moves the pointer to the next character in the file.
Format: $char = fgetc($fh);
fgetcsv
Reads a line of no longer than length from a file and returns it as an array, breaking it into elements at the specified separator, sep.
Format: $array_out = fgetcsv($fh,length,”sep”);
fgets, fgetss
Reads a line from file of no longer than length. Does not return the end-ofline character. fgetss also strips tags from line.
Format: $line = fgets($fh,length); $line=fgetss($fh,length);
file -->Reads a file and returns an array with one line per element.
Format: $array_lines = file($fh);
file_exists --> Checks whether a specific file exists. Returns TRUE or FALSE.
Format: $bool = file_exists(“pathtofile”);
fileatime --> Returns the time that the specified file was last accessed.
Format: $timestamp = fileatime(“pathtofilename”);
filectime --> Returns the time that the specified file was created.
Format: $timestamp = filectime(“pathtofilename”);
filemtime --> Returns the time that the specified file was last modified.
Format: $timestamp = filemtime(“pathtofile”);
fileowner --> Returns the user ID of the owner of the file.
Format: $userID = fileowner(“pathtofile”);
fileperms --> Returns the file permissions for the file.
Format: $perms = fileperms(“pathtofile”);
filesize --> Returns the file size in bytes.
Format: $size = filesize(“pathtofile”);
filetype --> Returns the file type, such a file or directory.
Format: $type = filetype(“pathtofile”);
flock --> Locks a file so that no one else can access it until it’s unlocked.
Format: flock($fh,mode);
fopen --> Opens a file and returns a pointer to the specified file.
Format: $fh = fopen(“pathtofile”,”mode”);
fputs
Writes text to a file. Alias for fwrite. Returns the number of bytes written to the file or FALSE if the function fails.
Format: $result = fputs($fh,”text”,length);
fread --> Reads number of bytes, unless it reaches the end of the file first, from a file.
Format: $file_content = fread($fh,number);
fscanf --> Reads text from a file and returns a formatted string.
Format: $string = fscanf($fh,”format”,$v1,$v2, . . .);
fseek
Moves the file pointer, depending on the next two parameters. The value specified in num is a number of characters. You can set mode to SEEK_SET (moves to char in position num), SEEK_CUR (moves num characters forward from current position), or SEEK_END (moves num characters back from the last character).
Format: fseek($fh,num,mode);
fwrite
Writes text to the file indicated by $fh, stopping at length. Specifying length is optional.
Format: $bytes_written = fputs($fh,”text”,length);
getcwd --> Returns the path to the current directory.
Format: $current_directory = getcwd();
getlastmod --> Returns the last modification date of the current script.
Format: $timestamp = getlastmod();
is_dir --> Checks whether the specified path is a directory.
Format: $bool = is_dir(“pathtodir”);
is_file --> Checks whether a specified file is a regular file, rather than a directory or special system file.
Format: $bool = is_file(“pathtofile”);
is_readable --> Checks whether a specified file is readable.
Format: $bool = is_readable(“pathtofile”);
is_uploaded_file --> Checks whether a specified file was uploaded via Web server form.
Format: $bool = is_uploaded_file(“pathtofile”);

is_writable --> Checks whether a specified file is writable.
Format: $bool = is_writable(“pathtofile”);
link --> Creates a hard link to path at newpath.
Format: link(“path”,”newpath”);
mkdir --> Creates a new directory. The value specified in mode is permissions in octal form.
Format: mkdir(“pathtonewdir”,mode);
move_uploaded_file --> Moves a file from its temporary upload directory to a permanent file.
Format: move_uploaded_file(“filename”,”pathtodestination”);
opendir --> Opens a directory. Returns a pointer to the open directory.
Format: $dh = opendir(“pathtodir”);
passthru --> Executes a system command and outputs the result.
Format: passthru(“systemcommand”);
pathinfo
Creates an array with information about a path. The array contains three elements: dirname, basename, and extension.
Format: $array_dir = pathinfo(“pathtodir”);
readdir --> Reads one filename from the open directory.
Format: $filename = readdir($dh);
readfile --> Reads a file and outputs the contents. Can handle a URL.
Format: $numberOfBytesRead = readfile(“pathtofile”);
rename --> Renames a file.
Format: rename(“oldfilename”,”newfilename”);
rewind --> Sets a file pointer to beginning of the file referred to by $fh.
Format: rewind($fh);
rmdir --> Removes a directory.
Format: rmdir(“pathtodir”);
tempnam --> Generates a unique filename with a specified prefix in the directory.
Format: $filename = tempnam(“pathtodir”,”prefix”);
tmpfile
Creates a temporary file with a unique name, opens it with write privileges, and returns a pointer to the open file.
Format: $fh = tmpfile();
touch
Sets the modification date of a file. If time isn’t specified, it sets the date to the current time. If the file does not exist, it’s created.
Format: $bool = touch(“pathtofile”,time);
umask
Sets the default permissions to mask and returns the previous mask. The previous defaults are restored at the end of the script.
Format: $old_mask = umask(mask);
unlink --> Deletes a file.
Format: unlink(“pathtofile”);

HTTP and Mail Functions

get_browser
Returns an object containing information about the user’s current browser or about the browser name if specified.
Format: $string = get_browser(“name”);
get_meta_tags
Creates an array, each element of which is a name attribute for any meta tags found in a file.
Format: $array_tags = get_meta_tags(“pathtofile”);
header --> Sends an HTTP header to the Web server.
Format: header(“HTTPformattedheader”);
mail --> Sends e-mail from a PHP script.
Format: $success = mail(“to”,”subj”,”message”,”headers”);
parse_url
Returns an array, each element of which is a part of the URL, such as host, path, port, user, and so on.
Format: $array_url = parse_url(“url”);
setcookie --> Creates a cookie.
Format:
setcookie(“name”,”value”,exp,”path”,”domain”,is_secure);

Mathematical Functions

abs --> Returns the absolute value of number.
Format: $absolute = abs(number);
bindec --> Converts binary to a decimal value.
Format: $number_decimal = bindec(binary);
exp --> Returns the constant e raised to the power specified in exponent.
Format: $number = exp(exponent);
floor --> Rounds float to the next lower integer.
Format: $int = floor(float);
hexdec --> Converts hex (a number in hexadecimal form) to decimal.
Format: $number_decimal = hexdec(hex);
log --> Returns the natural log of number.
Format: $log = log(number);
log10 --> Returns the base-10 logarithm of number.
Format: $log10 = log10(number);
max --> Returns the largest number found in an array or a list of numbers.
Format: $num_large = max($array); or $num_large = max(num1,num2,. . .);
min --> Returns the smallest number found in an array or a list of numbers.
Format: $num_min = min($array); or $num_min = min(num1,num2, . . .);
number_format
Formats a number with specified decimal (dec) and thousands separators (thous). The default is a standard decimal point (.) and a comma (,) for the thousands separators.
Format: $formatted = number_format(number,”dec”’,”thous”);
octdec --> Converts a number in octal form to decimal form.
Format: $number_decimal = octdec(octal);
pow --> Returns number raised to power.
Format: $result = pow(number,power);
rand --> Returns a random number between min and max.
Format: $number_rand = rand(min,max);
round --> Rounds number to the nearest number with the specified number of decimal places.
Format: $result = round(number,dec);
sqrt --> Returns the square root of number.
Format: $square_root = sqrt(number);

srand --> Seeds the random number generator with seed.
Format: srand(seed);
PHP Options and Information Functions This section contains functions that work with PHP options and information.
getenv --> Returns the value of an environmental variable.
Format: $environment_value = getenv(“envvarname”);
getlastmod --> Gets the time that the current script was last modified.
Format: $timestamp = getlastmod();
ini_get --> Gets the value for a configuration option.
Format: $string = ini_get(“option”);
ini_set --> Sets the value of a configuration option.
Format: ini_set(“option”,”setting”);
phpinfo --> Outputs information about your PHP version and settings.
Format: phpinfo();
phpversion --> Returns the current PHP version.
Format: $version = phpversion();
putenv
Sets an environments variable. The value indicated in setting is usually in the form name=value.
Format: putenv(“setting”);

String Functions

addslashes --> Escapes single quotes, double quotes, backslashes, and \0 in strings.
Format: $string_escaped = addslashes(“string”);
base64_encode, base64_decode
Encodes/decodes a string of base-64–coded characters, usually binary data.
Format: $string_encoded = base64_encode(“string”);
chop --> Truncates blank spaces at the end of a string.
Format: $chopped = chop(“string”);
chr --> Returns a single ASCII character for the number code.
Format: $char = chr(code)
count_chars
Creates an associative array out of a string. Each element has a character as a key, and the value is the number of that character in the string. This function has some options for only returning characters with count 0 or with nonzero and others. Default, when no options is specified, is all characters.
Format: $array = count_chars($string,option);
echo --> Outputs a list of one or more items. (See Chapter 3.)
Format: echo item1,item2,item3, . . .
ereg, eregi
Searches a string for pattern. The function eregi works the same but is case-insensitive. (See Chapter 7.)
Format: $bool = ereg(“pattern”,$string);
ereg_replace, eregi_replace
Searches a string for pattern & replaces pattern with newchar.Ereg_replace is case-sensitive; eregi_replace is not.
Format: $newstring = ereg_replace(“pattern”,”newchars”,$string);
explode --> Creates an array. Each element is part of the string, split at sep.
Format: $array_out = explode(“sep”,$string);
htmlentities --> Converts HTML entities to special characters in a string.
Format: $string_out = htmlentities($orig_string);
htmlspecialchars --> Converts special characters to HTML entities, such as & to &.
Format: $string_out($string);
implode --> Joins every element in an array into a string, separated by sep.
Format: $string_out = ($array,”sep”);
nl2br --> Inserts a
before all new line characters (\n) in $string.
Format: $string_out = ($string);
ord --> Returns the ASCII value of the first character in the string.
Format: $integer = ord(“string”);
parse_url --> Creates an associative array. Each element is part of the URL.
Format: $array = parse_url($url);
print --> Outputs item, where item can be a string, a number, or a variable.
Format: print item;
printf --> Outputs a string formatted according to format.
Format: printf(“format”,arg1,arg2,arg3, . . .);
split, spliti --> Creates array. Each element is part of a specified string, split based on the regular expression pattern. Split is case-sensitive; spliti is not.
Format: $array = split(“pattern”,$string); $array =spliti(“pattern”,$string);
sprintf --> Returns a string formatted according to format.
Format: $string = sprintf(“format”,arg1,arg2,arg3 . . .);
str_pad
Returns a string that is padded to make it number long. The character specified by pad is used to pad the string.
Format: $string_out = str_pad($string,numberh,”pad”);
str_repeat --> Returns a string that contains $string repeated number times.
Format: $string_out = str_repeat($string,number);
str_replace --> Finds all instances of oldtext in $string and replaces them with newtext.
Format: $string_out = str_replace(“oldtext”,”newtext”,$string)
strchr, strrchar
The function strchr returns part of string from char to end of $string, and strrchar returns $string from char to start of string.
Format: $string_part = strchr($string,”char”);
strcmp, strcasecmp
Compares two strings on alphabetical and numerical order . Returns @@n1 if str1 is less, 0 if two strings are equal, or +1 if str1 is greater. strcmp is casesensitive; strcasecmp is not.
Format: strcasecmp($str1,$str2);
strcspn --> Returns the position of the first occurrence of char in $string.
Format: $int = strcspn($string,”char”);
strip_tags
Removes HTML and PHP tags from string. The value allowed is optional and specifies tags that should not be stripped.
Format: $string_stripped = strinp_tags($string,”allowed”);
strlen --> Returns the number of characters in $string.
Format: $length = strlen($string);
strpos, strrpos
strpos returns the position of the first occurrence of char in $string. strrpos returns position of last occurrence of char in string.
Format: $integer = strpos($string,”char”); $integer =strrpos($string,”char”);
strspn
Returns the length of the substring in $string that matches text.
Format: $length = strspn($string,”text”);
strstr, stristr -->Returns part of $string from the first occurrence of char to end of $string. Strstr is case-sensitive; trichar is case-insensitive.
Format: $str_part = strstr($string,”char”); $str_part =strstr($string,”char”);
strtolower, strtoupper --> Converts $string to lowercase or uppercase.
Format: $string_lower = strtolower($string);
strtr --> Converts from characters in $string to characters in to.
Format: $string_out = strtr($string,”from”,”to”);
substr --> Returns a substring of $string. Starts at start and reads number characters.
Format: $substring = substr($string,start,number);
substr_replace --> Replaces a substring with newtext. Starts at start and reads number characters.
Format: $string_new =substr_replace($string,”newtext”,start,number);
trim, ltrim, rtrim
Removes whitespace characters from $string. The trim function removes from beginning and end; ltrim removes from beginning; rtrim removes from end.
Format: $string_new = trim($string);
ucfirst --> Converts first character in $string to uppercase.
Format: $string_new = ucfirst($string);
ucwords --> Converts first character of each word in $string to uppercase.
Format: $string_new = ucwords($string);
wordwrap --> Inserts end-of-line character (\r\n) into $string every length characters.
Format: $string_out = wordwrap($string,length);

Variable Functions

empty --> Tests whether the variable specified is empty.
Format: $bool = empty($varname);
get_defined_classes
Creates an array containing the names of all the classes in the script, including those in included files.
Format: $array_classes = get_defined_classes();
get_defined_constants --> Creates an associative array of all the constants.
Format: $array_constants = get_defined_constants();
get_defined_functions --> Creates an array with names of all functions.
Format: $array_functions = get_defined_functions();
get_defined_vars --> Creates an array of all variables.
Format: $array_vars = get_defined_vars();
isset --> Checks whether variable is set.
Format: $bool = isset($varname);
print_r --> Outputs contents of a variable.
Format: print_r($varname);
putenv --> Sets an environmental variable as specified by setting. setting is usually name=value.
Format: putenv(“setting”);
serialize
Converts data into a string containing binary data. Used to store data in a file or database. The specified variable can be any type, including an object or a function.
Format: $string_ser = serialize($variable);
unserialize --> Converts serialized data back to its original form.
Format: $variable = unserialize($string_ser);
unset --> Removes a variable.
Format: unset($varname);
var_dump --> Outputs contents of a variable.
Format: var_dump($varname);

Wednesday, January 28, 2009

User Contributed Notes in variable functions

example:

It may be useful to note that 'variable functions' can only be used in conjunction with functions, and not language constructs such as echo, die, exit, etc.

example:

If you want to call a static function (PHP5) in a variable method:

Make an array of two entries where the 0th entry is the name of the class to be invoked ('self' and 'parent' work as well) and the 1st entry is the name of the function. Basically, a 'callback' variable is either a string (the name of the function) or an array (0 => 'className', 1 => 'functionName').

Then, to call that function, you can use either call_user_func() or call_user_func_array(). Examples:

class A {

protected $a;
protected $c;

function __construct() {
$this->a = array('self', 'a');
$this->c = array('self', 'c');
}

static function a($name, &$value) {
echo $name,' => ',$value++,"\n";
}

function b($name, &$value) {
call_user_func_array($this->a, array($name, &$value));
}

static function c($str) {
echo $str,"\n";
}

function d() {
call_user_func_array($this->c, func_get_args());
}

function e() {
call_user_func($this->c, func_get_arg(0));
}

}

class B extends A {

function __construct() {
$this->a = array('parent', 'a');
$this->c = array('self', 'c');
}

static function c() {
print_r(func_get_args());
}

function d() {
call_user_func_array($this->c, func_get_args());
}

function e() {
call_user_func($this->c, func_get_args());
}

}

$a =& new A;
$b =& new B;
$i = 0;

A::a('index', $i);
$a->b('index', $i);

$a->c('string');
$a->d('string');
$a->e('string');

# etc.
?>
Storm
04-May-2005 01:34
This can quite useful for a dynamic database class:

(Note: This just a simplified section)

class db {

private $host = 'localhost';
private $user = 'username';
private $pass = 'password';
private $type = 'mysqli';

public $lid = 0;

// Connection function
function connect() {
$connect = $this->type.'_connect';

if (!$this->lid = $connect($this->host, $this->user, $this->pass)) {
die('Unable to connect.');
}
}
}
$db = new db;
$db->connect();
?>

Much easier than having multiple database classes or even extending a base class.

example:

A good method to pass around variables containing function names within some class is to use the same method as the developers use in preg_replace_callback - with arrays containing an instance of the class and the function name itself.

function call_within_an_object($fun)
{
if(is_array($fun))
{
/* call a function within an object */
$fun[0]->{$fun[1]}();
}
else
{
/* call some other function */
$fun();
}
}

function some_other_fun()
{
/* code */
}

class x
{
function fun($value)
{
/* some code */
}
}

$x = new x();

/* the following line calls $x->fun() */
call_within_an_object(Array($x, 'fun'));

/* the following line calls some_other_fun() */
call_within_an_object('some_other_fun');

example:

Finally, a very easy way to call a variable method in a class:

Example of a class:

class Print() {
var $mPrintFunction;

function Print($where_to) {
$this->mPrintFunction = "PrintTo$where_to";
}

function PrintToScreen($content) {
echo $content;
}

function PrintToFile($content) {
fputs ($file, $contents);
}

.. .. ..

// first, function name is parsed, then function is called
$this->{$this->mPrintFunction}("something to print");
}

example:

Try the call_user_func() function. I find it's a bit simpler to implement, and at very least makes your code a bit more readable... much more readable and simpler to research for someone who isn't familiar with this construct.
anpatel at NOSPAM_cbu dot edu
18-Mar-2002 04:11
Yes interpolation can be very tricky. I suggest that you always use parenthesis, or curly brackets(whichever applies) to make your expression clear.

Dont ever depend on a language's expression parse preference order.
retro at enx dot org
14-Jan-2002 02:18
Another way to have php parse a variable within an object as a function is to simply set a temporary variable to its value. For example:

$obj->myfunction = "foo";
$x = $obj->myfunction;
$x(); // calls the function named "foo"