You are on page 1of 65

PHP reference by Jan Zumwalt

Pg 1 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Blank Page

PHP reference by Jan Zumwalt

Pg 2 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Table of Contents
Table of Contents ........................................................................................................................................ 3 PHP Syntax .................................................................................................................................................. 5 PHP Information........................................................................................................................................... 5 PHP From the Command Line..................................................................................................................... 6 Variables ...................................................................................................................................................... 6
Example PHP variable with numbers............................................................................................................................ 6

$_SERVER variables.................................................................................................................................... 7 Array functions ............................................................................................................................................ 9 Array constants ......................................................................................................................................... 11 null, , , empty( ), and special values .................................................................................................. 12 comparison with == ................................................................................................................................... 12 comparison with === ................................................................................................................................. 13 String Functions ........................................................................................................................................ 14 String manipulation ................................................................................................................................... 16
Example PHP String ................................................................................................................................................... 16 Single and Double Quotes ............................................................................................................................................. 16 Example String in Double Quotes ............................................................................................................................... 16 Example String in Single Quotes ................................................................................................................................ 16 Concatenating................................................................................................................................................................ 17 strlen() - number of characters in a string ...................................................................................................................... 17 str_replace() - replaces all occurrences ......................................................................................................................... 17 strtoupper() convert to upper case .............................................................................................................................. 18 ucfirst() first letter to upper case.................................................................................................................................. 18 trim() - remove start and end blanks .............................................................................................................................. 18

If Else Statement........................................................................................................................................ 19
Example Without Curly Brackets................................................................................................................................. 19 Example With Curly Brackets...................................................................................................................................... 19 Example Elseif Statement ........................................................................................................................................... 20

For Loops ................................................................................................................................................... 20


Template ........................................................................................................................................................................ 20 Example For Loop...................................................................................................................................................... 20 Example Print table with zebra stripes using PHP FOR Loop..................................................................................... 21

While Loops ............................................................................................................................................... 22


While Loop Syntax ......................................................................................................................................................... 22 Example While Loop ................................................................................................................................................... 22 Breaking out of a PHP Loop........................................................................................................................................... 22

Arrays ......................................................................................................................................................... 23
Numeric Arrays .............................................................................................................................................................. 23 Creating an Numeric Array............................................................................................................................................. 23 Example 1 Numeric Array individual assignment ..................................................................................................... 23 Example 2 Numeric Array inline assignment............................................................................................................ 23 Example 3 Associative Array (key-value pairs) ........................................................................................................ 23 Example 4 Associative Array Object (pointer) syntax .............................................................................................. 23 Multidimensional Arrays ................................................................................................................................................. 24 Employees Table/Matrix ................................................................................................................................................ 24 Creating Multi-dimensional Array in PHP ....................................................................................................................... 24 Example 5 Associative Multi-dimensional Arrays ........................................................................................................ 24 Example 6 Pointer Multi-dimensional Arrays............................................................................................................... 24 print_r() Printing Arrays ............................................................................................................................................... 25

Date & Time................................................................................................................................................ 26


Calendar functions ......................................................................................................................................................... 26 PHP Date Function Syntax ............................................................................................................................................ 26 PHP Date: strtotime()..................................................................................................................................................... 26 Find Yesterdays date .................................................................................................................................................... 27 Find Date one week ago ................................................................................................................................................ 27 Find Date one month after ............................................................................................................................................. 27 PHP Date: mktime() ....................................................................................................................................................... 27 Find Leap Year .............................................................................................................................................................. 27

File IO ......................................................................................................................................................... 29
File functions.................................................................................................................................................................. 29

PHP reference by Jan Zumwalt

Pg 3 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Opening a file file modes............................................................................................................................................. 30 What if file doesn't exist? ............................................................................................................................................... 31 is_file() Testing if file or dir exists ................................................................................................................................ 31 Open at end of file.......................................................................................................................................................... 31 fgets() Read Line ........................................................................................................................................................ 31 Reading entire line ......................................................................................................................................................... 31 Reading number of bytes ............................................................................................................................................... 32 Reading file line by line .................................................................................................................................................. 32 file_get_contents() read entire file ............................................................................................................................... 33 fwrite() writing to file .................................................................................................................................................... 33 Write text to a file ........................................................................................................................................................... 33 Write at beginning of a file.............................................................................................................................................. 34 Write at end of a file ....................................................................................................................................................... 34 Write string with line breaks ........................................................................................................................................... 35 Simultaneous Read / Write ............................................................................................................................................ 35

Directory functions .................................................................................................................................... 37 Remote File IO ........................................................................................................................................... 38


Example 1 open remote files....................................................................................................................................... 38

Forms ......................................................................................................................................................... 39
Useful form commands .................................................................................................................................................. 39 Redirection and new windows........................................................................................................................................ 39 Input form visitor_form.php ......................................................................................................................................... 39 Process form visitor_info.php...................................................................................................................................... 39 Drop Down Box.............................................................................................................................................................. 40 Email.............................................................................................................................................................................. 40 Sending Plain Text Email ............................................................................................................................................... 40 Sending HTML Email ..................................................................................................................................................... 41 Remote input and processing Email .............................................................................................................................. 41 Input form email.php ................................................................................................................................................... 41 Processing program sendmail.php.............................................................................................................................. 42

Sessions..................................................................................................................................................... 44
Storing information in a session ..................................................................................................................................... 44 Retrieving stored session information ............................................................................................................................ 44 Destroying/deleting session information ........................................................................................................................ 44

Regex ......................................................................................................................................................... 46
Test for string occurrence: ............................................................................................................................................. 46 Replace string occurrence: ............................................................................................................................................ 46 preg_match functions..................................................................................................................................................... 46 Common regex operators .............................................................................................................................................. 46 Examples ....................................................................................................................................................................... 47

Cookies ...................................................................................................................................................... 49
Creating a permanent cookie ......................................................................................................................................... 49 Retrieving a cookie ........................................................................................................................................................ 49 Deleting a Cookie........................................................................................................................................................... 50

Miscellaneous functions ........................................................................................................................... 51 MySql.......................................................................................................................................................... 52


Security .......................................................................................................................................................................... 57 Unix File Permissions .................................................................................................................................................... 57 HTML Output ................................................................................................................................................................. 58 Error Trapping................................................................................................................................................................ 59

PHP reference by Jan Zumwalt

Pg 4 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

PHP Syntax
<html> <title>my php page</title> <body> <h1>PHP Test</H1> <?php // Single line comment /* * multi-line * comment */ echo echo echo echo ?> </body> </html> "hello there!"; "<b>hello there!</b>"; "<font color='green'>hello there!</font>"; "today is ".date('Y-m-d');

Note: At the end of each PHP statement is a semicolon, i.e. ";". If this is omitted, PHP will report an error.

PHP Information
<?php session_start(); echo "<body>" . "<center><h1><span style='color:red;'>PHP Info & Varibles</span></h1></center>"; phpinfo(); // show all OS varibles echo . . . "<table align=center cellpadding=50>" "<tr><td width=500>" "<h1><span style='color:red;'>Var Dump</span></h1>" "<pre>"; var_dump(get_defined_vars()); echo "</pre>" . "</td></tr>"; echo . . . "<tr><td>" "<h1><span style='color:red;'>SESSION Varibles</span></h1>" "<br>" "<pre>"; print_r($_SESSION); echo "</pre>" . "</td></tr>"; echo . . . "<tr><td>" "<h1><span style='color:red;'>POST Varibles</span></h1>" "<br>" "<pre>"; print_r($_POST); echo "</pre>" . "</td></tr>"; echo . . . "<tr><td>" "<h1><span style='color:red;'>GET Varibles</span></h1>" "<br>" "<pre>"; print_r($_GET); echo "</pre>" . "</td></tr>"; echo "</table>" . "</body>"; ?>

PHP reference by Jan Zumwalt

Pg 5 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

PHP From the Command Line


c:\xampp\php\php -c C:\windows\php.ini -r "phpinfo();"

Variables
PHP variables start with a $ sign. A variable name should only start with an underscore "_" or a letter. A variable can only contain letters, numbers or an underscore. In another words, we can't use characters like < ^ # in our variable names.
<?php $str = "I love PHP"; // variable with a string value echo $str; // print the $str value to the browser $num = 100; echo $num . " "; echo $str; echo $num; ?> // another variable with a integer value // using echo to print the $num variable // reuse the $str variable to print its value // reuse the $num variable to print its value

Result:

I Love PHP100 - I Love PHP100 (notice we did not send a line break)

Example PHP variable with numbers


<?php $integer_number = 100; echo $number; ?> <?php $decimal_number = 100.01; printf("%.2f", $decimal_number); ?>

PHP reference by Jan Zumwalt

Pg 6 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

$_SERVER variables
'PHP_SELF' 'argv' /test.php/index.php The filename of executing script relative to document root. Array of arguments passed to the script. Command line gives C-style parameters. GET method returns query string. Contains the number of command line parameters passed to the script (if run on the command line). CGI/1.1 What revision of the CGI specification the server is using. 'SERVER_ADDR' 'SERVER_NAME' 'SERVER_SOFTWARE' 'SERVER_PROTOCOL' The IP address of the server under which the current script is executing. server host name Server identification string, given in the headers when responding to requests. HTTP/1.0 Name and revision of the page protocol. 'REQUEST_METHOD' GET', 'HEAD', 'POST', 'PUT Request method used to access the page. 'REQUEST_TIME' 'REQUEST_TIME_FLOAT' 'QUERY_STRING' 'DOCUMENT_ROOT' 'HTTP_ACCEPT' 'HTTP_ACCEPT_CHARSET' The timestamp of the start of request. The timestamp with microsecond of the start of request, The query string, if any, via which the page was accessed. Document root directory of current script. Contents of the Accept: header from the current request, if there is one. 'iso-8859-1,*,utf-8' Contents of the Accept-Charset: header from the current request, if there is one. 'HTTP_ACCEPT_ENCODING' 'gzip' Contents of the Accept-Encoding: header from the current request, if there is one. 'HTTP_ACCEPT_LANGUAGE' 'en' Contents of the Accept-Language: header from the current request, if there is one. 'HTTP_CONNECTION' 'Keep-Alive' Contents of the Connection: header from the current request, if there is one. 'HTTP_HOST' 'HTTP_REFERER' 'HTTP_USER_AGENT' Contents of the Host: header, if there is one. Address of calling page (often not provided). Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586) Contents of the User-Agent: 'HTTPS' Set to a non-empty value if the script was queried through the HTTPS protocol.

'argc' 'GATEWAY_INTERFACE'

PHP reference by Jan Zumwalt

Pg 7 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

'REMOTE_ADDR' 'REMOTE_HOST'

The IP address from which the user is viewing the current page. The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user. User machine port used to communicate with web server. The authenticated user. The authenticated user if the request is internally redirected. The absolute pathname of the currently executing script. The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host. '80' Server machine port used for web server for communication.

'REMOTE_PORT' 'REMOTE_USER' 'REDIRECT_REMOTE_USER' 'SCRIPT_FILENAME' 'SERVER_ADMIN'

'SERVER_PORT'

'SERVER_SIGNATURE' 'PATH_TRANSLATED' 'SCRIPT_NAME' 'REQUEST_URI' 'PHP_AUTH_DIGEST'

Server version and virtual host name. Filesystem- (not document root-) based path to the current script, Current script's path. The URI which was given in order to access this page; for instance, '/index.html'. When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation). When doing HTTP authentication this variable is set to the username provided by the user. When doing HTTP authentication this variable is set to the password provided by the user. When doing HTTP authenticated this variable is set to the authentication type. Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff. Original version of 'PATH_INFO' before processed by PHP.

'PHP_AUTH_USER' 'PHP_AUTH_PW' 'AUTH_TYPE' 'PATH_INFO'

'ORIG_PATH_INFO'

PHP reference by Jan Zumwalt

Pg 8 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Array functions
Function
array() array_change_key_case() array_chunk() array_combine() array_count_values() array_diff() array_diff_assoc() array_diff_key() array_diff_uassoc() array_diff_ukey() array_fill() array_filter() array_flip() array_intersect() array_intersect_assoc() array_intersect_key() array_intersect_uassoc() array_intersect_ukey() array_key_exists() array_keys() array_map() array_merge() array_merge_recursive() array_multisort() array_pad() array_pop() array_product() array_push() array_rand() array_reduce() array_reverse() array_search() array_shift() array_slice() array_splice() array_sum() array_udiff() array_udiff_assoc()

Description
Creates an array Returns an array with all keys in lowercase or uppercase Splits an array into chunks of arrays Creates an array by using one array for keys and another for its values Returns an array with the number of occurrences for each value Compares array values, and returns the differences Compares array keys and values, and returns the differences Compares array keys, and returns the differences Compares array keys and values, with an additional user-made function check, and returns the differences Compares array keys, with an additional user-made function check, and returns the differences Fills an array with values Filters elements of an array using a user-made function Exchanges all keys with their associated values in an array Compares array values, and returns the matches Compares array keys and values, and returns the matches Compares array keys, and returns the matches Compares array keys and values, with an additional user-made function check, and returns the matches Compares array keys, with an additional user-made function check, and returns the matches Checks if the specified key exists in the array Returns all the keys of an array Sends each value of an array to a user-made function, which returns new values Merges one or more arrays into one array Merges one or more arrays into one array Sorts multiple or multi-dimensional arrays Inserts a specified number of items, with a specified value, to an array Deletes the last element of an array Calculates the product of the values in an array Inserts one or more elements to the end of an array Returns one or more random keys from an array Returns an array as a string, using a user-defined function Returns an array in the reverse order Searches an array for a given value and returns the key Removes the first element from an array, and returns the value of the removed element Returns selected parts of an array Removes and replaces specified elements of an array Returns the sum of the values in an array Compares array values in a user-made function and returns an array Compares array keys, and compares array values in a user-made

PHP reference by Jan Zumwalt

Pg 9 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

function, and returns an array array_udiff_uassoc() array_uintersect() array_uintersect_assoc() array_uintersect_uassoc() array_unique() array_unshift() array_values() array_walk() array_walk_recursive() arsort() asort() compact() count() current() each() end() extract() in_array() key() krsort() ksort() list() natcasesort() natsort() next() pos() prev() range() reset() rsort() shuffle() sizeof() sort() uasort() uksort() usort() Compares array keys and array values in user-made functions, and returns an array Compares array values in a user-made function and returns an array Compares array keys, and compares array values in a user-made function, and returns an array Compares array keys and array values in user-made functions, and returns an array Removes duplicate values from an array Adds one or more elements to the beginning of an array Returns all the values of an array Applies a user function to every member of an array Applies a user function recursively to every member of an array Sorts an array in reverse order and maintain index association Sorts an array and maintain index association Create array containing variables and their values Counts elements in an array, or properties in an object Returns the current element in an array Returns the current key and value pair from an array Sets the internal pointer of an array to its last element Imports variables into the current symbol table from an array Checks if a specified value exists in an array Fetches a key from an array Sorts an array by key in reverse order Sorts an array by key Assigns variables as if they were an array Sorts an array using a case insensitive "natural order" algorithm Sorts an array using a "natural order" algorithm Advance the internal array pointer of an array Alias of current() Rewinds the internal array pointer Creates an array containing a range of elements Sets the internal pointer of an array to its first element Sorts an array in reverse order Shuffles an array Alias of count() Sorts an array Sorts an array with a user-defined function and maintain index association Sorts an array by keys using a user-defined function Sorts an array by values using a user-defined function

PHP reference by Jan Zumwalt

Pg 10 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Array constants
Constant CASE_LOWER CASE_UPPER SORT_ASC SORT_DESC SORT_REGULAR SORT_NUMERIC SORT_STRING SORT_LOCALE_STRING COUNT_NORMAL COUNT_RECURSIVE EXTR_OVERWRITE EXTR_SKIP EXTR_PREFIX_SAME EXTR_PREFIX_ALL EXTR_PREFIX_INVALID EXTR_PREFIX_IF_EXISTS EXTR_IF_EXISTS EXTR_REFS Description Used with array_change_key_case() to convert array keys to lower case Used with array_change_key_case() to convert array keys to upper case Used with array_multisort() to sort in ascending order Used with array_multisort() to sort in descending order Used to compare items normally Used to compare items numerically Used to compare items as strings Used to compare items as strings, based on the current locale

PHP reference by Jan Zumwalt

Pg 11 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

null, , , empty( ), and special values


gettype() empty() is_null() isSet() (bool) $x = ""; $x = null; string NULL true true true true true false false true false false false true false false false false false true true false false false false false false false false false false false false false true false false true true true true true true true true true true true true true false false false false false true true false true true true false true true true true

var $x; (not set) NULL $x = array(); $x = false; $x = 15; $x = 1; $x = 0; $x = -1; $x = "15"; $x = "1"; $x = "0"; $x = "-1"; $x = "foo"; $x = "true"; $x = "false"; array boolean integer integer integer integer string string string string string string string

Note: empty() and isSet() don't give warnings when the variables have not been previously defined.

comparison with ==
true true false 1 0 -1 "1" "0" "-1" "1.3" "1.30" 1.3 1.30 true false 1 false true 0 -1 "1" true "0" "-1" "1.3" "1.30" 1.3 true true true 1.30 true array() "foo" "" false true false false true false true

false true true

false true

false false true

false false false

false false true false false false false false false false false false false false false false false false false false false true true true true true true true true false false false false

false true false false true true

false true

false false true

false false false false false false false false false

false true true true

false true

false false true

false false false true false true

false false true

false false false false false false false false false false false false false false false false false false true false

false false true

false false false false false false false false false true true true true

false true true true true true true

false true

false false true

false false false true

false false true

false false false false false false false true false false false false false false false true false false false false false false false true false false false false false false false true

array() false true "foo" "" true

false false false false false false false false false false false false false false false false false false false false

false false true false false false false false false

false false true false true

false true

false true

PHP reference by Jan Zumwalt

Pg 12 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

comparison with ===


true true false 1 0 -1 "1" "0" "-1" "1.3" "1.30" 1.3 1.30 true false 1 0 -1 "1" "0" "-1" "1.3" "1.30" 1.3 1.30 array() "foo" "" false false false false false false false false false false false false false false false false false false false false false false false false false false true false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false false true true true true false false

false true

false false true

false false false true

false false false false true

false false false false false true

false false false false false false true

false false false false false false false true

false false false false false false false false true

false false false false false false false false false true false false false false false false false false false false false false false false false false false false false false

array() false false false false false false false false false false "foo" "" false false false false false false false false false false false false false false false false false false false false

false false true false false false false false false

false true

PHP reference by Jan Zumwalt

Pg 13 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

String Functions
addcslashes() Quote string with slashes in a C style addslashes() Quote string with slashes bin2hex() Convert binary data into hexadecimal representation chop() Alias of rtrim chr() Return a specific character chunk_split() Split a string into smaller chunks convert_cyr_string() Convert from one Cyrillic character set to another convert_uudecode() Decode a uuencoded string convert_uuencode() Uuencode a string count_chars() Return information about characters used in a string crc32() Calculates the crc32 polynomial of a string crypt() One-way string hashing echo() Output one or more strings explode() Split a string by string fprintf() Write a formatted string to a stream get_html_translation_table() Returns html translation table for special chars hebrev() Convert logical Hebrew text to visual text hebrevc() Convert logical Hebrew text to visual text with newline conversion html_entity_decode() Convert all HTML entities to their applicable characters htmlentities() Convert all applicable characters to HTML entities htmlspecialchars_decode() Convert special HTML entities back to characters htmlspecialchars() Convert special characters to HTML entities implode() Join array elements with a string join() Alias of implode lcfirst() Make a string's first character lowercase levenshtein() Calculate Levenshtein distance between two strings localeconv() Get numeric formatting information ltrim() Strip whitespace (or other characters) from the beginning of a string md5_file() Calculates the md5 hash of a given file md5() Calculate the md5 hash of a string metaphone() Calculate the metaphone key of a string money_format() Formats a number as a currency string nl_langinfo() Query language and locale information nl2br() Inserts HTML line breaks before all newlines in a string number_format() Format a number with grouped thousands ord() Return ASCII value of character parse_str() Parses the string into variables print() Output a string (echo is faster) printf() Output a formatted string quoted_printable_decode() Convert a quoted-printable string to an 8 bit string quoted_printable_encode() Convert a 8 bit string to a quoted-printable string quotemeta() Quote meta characters rtrim() Strip whitespace (or other characters) from the end of a string setlocale() Set locale information sha1_file() Calculate the sha1 hash of a file sha1() Calculate the sha1 hash of a string similar_text() Calculate the similarity between two strings soundex() Calculate the soundex key of a string sprintf() Return a formatted string sscanf() Parses input from a string according to a format str_getcsv() Parse a CSV string into an array str_ireplace() Case-insensitive string replace. str_pad() Pad a string to a certain length with another string str_repeat() Repeat a string str_replace() Replace all occurrences of the search string with the replacement string

PHP reference by Jan Zumwalt

Pg 14 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

str_rot13() Perform the rot13 transform on a string str_shuffle() Randomly shuffles a string str_split() Convert a string to an array str_word_count() Return information about words used in a string strcasecmp() Binary safe case-insensitive string comparison strchr() Alias of strstr strcmp() Binary safe string comparison strcoll() Locale based string comparison strcspn() Find length of initial segment not matching mask strip_tags() Strip HTML and PHP tags from a string stripcslashes() Un-quote string quoted with addcslashes stripos() Find position of first occurrence of a case-insensitive string stripslashes() Un-quotes a quoted string stristr() Case-insensitive strstr strlen() Get string length strnatcasecmp() Case insensitive string comparisons using a "natural order" algorithm strnatcmp() String comparisons using a "natural order" algorithm strncasecmp() Binary safe case-insensitive string comparison of the first n characters strncmp() Binary safe string comparison of the first n characters strpbrk() Search a string for any of a set of characters strpos() Find position of first occurrence of a string strrchr() Find the last occurrence of a character in a string strrev() Reverse a string strripos() Find position of last occurrence of a case-insensitive string in a string strrpos() Find position of last occurrence of a char in a string strspn() Finds length of first string segment consisting entirely of characters in mask. strstr() Find first occurrence of a string strtok() Tokenize string strtolower() Make a string lowercase strtoupper() Make a string uppercase strtr() Translate certain characters substr_compare() Binary safe comparison of 2 strings from an offset, up to length characters substr_count() Count the number of substring occurrences substr_replace() Replace text within a portion of a string substr() Return part of a string trim() Strip whitespace (or other characters) from the beginning and end of a string ucfirst() Make a string's first character uppercase ucwords() Uppercase the first character of each word in a string vfprintf() Write a formatted string to a stream vprintf() Output a formatted string vsprintf() Return a formatted string wordwrap() Wraps a string to a given number of characters

PHP reference by Jan Zumwalt

Pg 15 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

String manipulation
A string is a sequence of letters, symbols, characters and numbers or combination of all of these tied together in single or double quotes. Tip: The print() function is slightly slower than echo() because print() calls echo() to do its work for it. Example PHP String
<?php $str = "I Love PHP"; echo $str ?>

Single and Double Quotes Double quotes allow the escape of specials characters in our string. For example, single quotes can be used within double quotes. Special characters are escaped using backslash. Sometimes special characters need to be escaped in strings. This is covered in the following section. Example String in Double Quotes
<?php $str = "It's a nice day today." echo $str; ?>

or
<?php $name = "Matt"; echo "Hello $name!"; ?>

Double quotes allow single quotes and special characters to be used. A character is ignored by preceding it with a backslash.
<?php $str = "\"This is a PHP string example in double quotes\""; echo $str; ?>

Example String in Single Quotes


<?php $str = 'This is a PHP string examples in single quotes'; echo $str; echo '<input type="text" name="first_name" id="first_name">'; ?>

or
<?php print ' <center><h1>Important</h1></center> <p>This is a lot of html code<br />

PHP reference by Jan Zumwalt

Pg 16 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

that can be displayed using a<br /> single print statement and single<br /> quote</p>' // end of print ?>

Single quotes allow double quotes in the string. Single quotes should be used when outputting HTML code. Special characters are escaped bu using a backslash in single quotes too.
<?php $str = 'It\'s a nice day today.'; echo $str; ?>

Concatenating While working with strings in our code, we may need to join two strings. In PHP, we can use '.' to concatenate two or more strings together to form a single string. Example 1 - $str1.$str2
<?php $str1 = "I Love PHP."; $str2 = "PHP is fun to learn."; echo $str1." ".$str2; ?>

Example 2 $str1.text
<?php $str1 = "I Love PHP."; $str2 = $str1." PHP is fun to learn."; echo $str2; ?>

Example 3 $str1 . = text


<?php $str1 = "I Love PHP."; $str1 . = " PHP is fun to learn."; echo $str1; ?>

strlen() - number of characters in a string


<?php $str = "Hello!"; echo strlen($str); ?>

Result: 6. str_replace() - replaces all occurrences


<?php $str = "Hello! How are we today?"; echo str_replace("Hello", "Hi", $str); ?>
Result: Hi! How are we today?

PHP reference by Jan Zumwalt

Pg 17 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

strtoupper() convert to upper case


<?php $str = "hello!"; echo strtoupper($str); ?>
Result: HELLO!

ucfirst() first letter to upper case


<?php $str = "hello!"; echo ucfirst($str); ?>
Result: Hello!

trim() - remove start and end blanks


<?php $str = " hello! "; echo trim($str); ?>
Result: hello!

PHP reference by Jan Zumwalt

Pg 18 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

If Else Statement
if (condition1){ statement(s); }

or if (condition1){ statement(s); }else{ statement(s); }

or if (condition1){ statement(s); } elseif (condition2){ statement(s); }

or if (condition1){ statement(s); }elseif(condition2){ statement(s); }else{ statement(s); }

Example Without Curly Brackets If there is only one line of code between the conditions, the brackets are not needed.
<html> <body> <?php // Give what day of the week it is. Returns Sunday through Saturday. $day = date("l"); if ($day == "Saturday") echo "It's party time :)"; else echo "Ahhh! I hate work days."; ?> </body> </html>

Example With Curly Brackets


<html> <body> <?php

PHP reference by Jan Zumwalt

Pg 19 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

//Give what day of the week it is. Returns Sunday through Saturday. $day = date("l"); if ($day == "Saturday") { echo "It's party time :)"; echo " Where are we going this evening?"; }else{ echo "Ahhh! I hate work days."; echo " I want weekend to come :)"; } ?> </body> </html>

Example Elseif Statement


<html> <body> <?php // Give what day of the week it is. Returns Sunday through Saturday. $day = date("l"); if ($day == "Saturday") { echo "It's party time :)"; echo " Where are we going this evening?"; }elseif ($day == "Friday") { echo "Have a nice day!"; }else{ echo "Ahhh! I hate work days."; echo " I want weekend to come :)"; } ?> </body> </html>

For Loops
Template
for(initialize; condition; increment) { //execute block of code }

Example For Loop


<?php for($i=0; $i<=5; $i=$i+1) { echo $i." "; } ?>
Result: numbers will be output 0 to 5 as 0 1 2 3 4 5.

In the above example, we set a counter variable $i to 0. In the second statement, we set the condition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we set $i to increment by 1. This code will output numbers 0 to 5 as 0 1 2 3 4 5. Note: The third increment statement can be set to increment by any number. In our above example, we can set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.

PHP reference by Jan Zumwalt

Pg 20 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Example Print table with zebra stripes using PHP FOR Loop You may have seen table cells with alternate colors. Here is how we can do that.
<?php echo "<table width='100' align='center'>"; for($i=0; $i<=5; $i=$i+1) { echo "<tr>"; echo "<td style='background-color: "; if($i % 2 == 0) { // different color for odd/even lines echo "red>"; }else{ echo "green>"; } // code... cell data goes here echo $i; echo "</td>"; echo "</tr>"; } // end of for echo "</table>"; ?> 0 1 2 3 4 5

PHP reference by Jan Zumwalt

Pg 21 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

While Loops
While Loop Syntax
while(condition) { //execute block of code }

Example While Loop


<?php $i = 1; while ($i <= 5 ) { echo $i . "<br>"; $i = $i + 1; } ?>
Result: 1 2 3 4 5

Breaking out of a PHP Loop Sometimes when we are working with loops, we want to break the loop when a certain condition is true. We can use the break; statement to stop the loop from executing.
<?php $i = 1; while ($i <= 5 ) { if($i == 4) break; // or continue echo $i . "<br>"; $i = $i + 1; } ?>
Result: The loop outputs... 1 2 3 then breaks

PHP reference by Jan Zumwalt

Pg 22 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Arrays
There are two types of arrays in PHP. Numeric Arrays Associative Arrays

Numeric Arrays In a numeric array we store each element with a numeric ID key. Creating an Numeric Array There are two ways to create a numeric array. Lets look at each example to see how it is done. Example 1 Numeric Array individual assignment
<?php $employee_names[0] = "Dana"; $employee_names[1] = "Matt"; $employee_names[2] = "Susan"; echo echo echo echo echo ?> "The first employee's name is ".$employee_names[0]; "<br>"; "The second employee's name is ".$employee_names[1]; "<br>"; "The third employee's name is ".$employee_names[2];

Result:
The first employee's name is Dana The second employee's name is Matt The third employee's name is Susan

Example 2 Numeric Array inline assignment


<?php $employee_names = array("Dana", "Matt", "Susan"); echo "The third employee's name is ".$employee_names[2]; ?>

Result: The third employee's name is Susan Example 3 Associative Array (key-value pairs)
<?php $employee_title["Dana"] = "Owner"; $employee_title["Matt"] = "Manager"; $employee_title["Susan"] = "Cashier"; echo "Matt is the ".$employee_title["Matt"]; ?>

Example 4 Associative Array Object (pointer) syntax


<?php $employee_names = array("Dana" => "Owner", "Matt" => "Manager", "Susan" => "Cashier");

PHP reference by Jan Zumwalt

Pg 23 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

echo "Matt is the ".$employee_names["Matt"]; ?>


Result:

Matt is the Manger

Multidimensional Arrays Lets extend our idea of associating a single key to an element. What if we want to associate multiple keys to an element? Consider the Employees Table/Matrix below. Employees Table/Matrix name title salary employee 1 Dana Owner $60,000 employee 2 Matt Manager $40,000 employee 3 Susan Clerk $30,000 Hmmm, that's nice but how would we store an employees table in an array? PHP provides a way of doing this using multidimensional array. The examples below show how this is done. Creating Multi-dimensional Array in PHP Again, there are two ways to create a multidimensional array. Lets look at each way of doing this. Example 5 Associative Multi-dimensional Arrays
<?php $employees["employee 1"]["name"] = "Dana"; $employees["employee 1"]["title"] = "Owner"; $employees["employee 1"]["salary"] = "$60,000"; $employees["employee 2"]["name"] = "Matt"; $employees["employee 2"]["title"] = "Manager"; $employees["employee 2"]["salary"] = "$40,000"; $employees["employee 3"]["name"] = "Susan"; $employees["employee 3"]["title"] = "Cashier"; $employees["employee 3"]["salary"] = "$30,000"; echo " " " ?> $employees["employee 2"]["name"]. is the ".$employees["employee 2"]["title"]. and earns ".$employees["employee 2"]["salary"]. a year.";

The above code creates a multi-dimensional array name of employees. Result:


Matt is the Manager and earns $40,000 a year.

Example 6 Pointer Multi-dimensional Arrays


<?php $employees = array ( "employee 1" => array ( "name" => "Dana", "title" => "Owner",

PHP reference by Jan Zumwalt

Pg 24 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

"salary" => "$60,000", ), "employee 2" => array ( "name" => "Matt", "title" => "Manager", "salary" => "$40,000", ), "employee 3" => array ( "name" => "Susan", "title" => "Cashier", "salary" => "$30,000", ) ); echo " " " ?> $employees["employee 1"]["name"]. is the ".$employees["employee 1"]["title"]. and earns ".$employees["employee 1"]["salary"]. a year.";

The above code creates a multi-dimensional array of employees.


Result: Dana is the Owner and earns $60,000 a year.

print_r() Printing Arrays To print the results of an array we can use the PHP function print_r(). Lets use an example
<?php $employee_title["Dana"] = "Owner"; $employee_title["Matt"] = "Manager"; $employee_title["Susan"] = "Cashier"; echo "<pre>"; print_r($employee_title); echo "</pre>"; ?>

The array result will print out as follows...


Array ( [Dana] => Owner [Matt] => Manager [Susan] => Cashier )

Note: Always remember to use <pre></pre> tags while printing an array as shown above otherwise the result is not very reader friendly.

PHP reference by Jan Zumwalt

Pg 25 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Date & Time


Calendar functions
Function cal_days_in_month() cal_from_jd() cal_info() cal_to_jd() easter_date() easter_days() FrenchToJD() GregorianToJD() JDDayOfWeek() JDMonthName() JDToFrench() JDToGregorian() jdtojewish() JDToJulian() jdtounix() JewishToJD() JulianToJD() unixtojd() Description Returns the number of days in a month for a specified year and calendar Converts a Julian day count into a date of a specified calendar Returns information about a given calendar Converts a date to Julian day count Returns the Unix timestamp for midnight on Easter of a specified year Returns the number of days after March 21, on which Easter falls for a specified year Converts a French Republican date to a Julian day count Converts a Gregorian date to a Julian day count Returns the day of a week Returns a month name Converts a Julian day count to a French Republican date Converts a Julian day count to a Gregorian date Converts a Julian day count to a Jewish date Converts a Julian day count to a Julian date Converts a Julian day count to a Unix timestamp Converts a Jewish date to a Julian day count Converts a Julian date to a Julian day count Converts a Unix timestamp to a Julian day count

PHP Date Function Syntax


date(format[, timestamp]) <?php echo echo echo echo echo echo echo echo ?>

date("Y-m-d"); date("Y/m/d"); date("M d, Y"); date("F d, Y"); date("D M d, Y"); date("l F d, Y"); date("l F d, Y, h:i:s"); date("l F d, Y, h:i A");

// 2010-03-19 // 2010-03-19 // Mar 19, 2010 // March 19, 2010 // Fri Mar 19, 2010 // Friday March 19, 2010 // Friday March 19, 2010, 04:20:36 // Friday March 19, 2010, 04:20 PM

Where:
d - The day of the month, i.e. 01-31 m - Month representation in numbers, i.e. 01-12 Y - Year in four digits timestamp, is an optional parameter representing the number of seconds since January 1, 1970 at 00:00:00

GMT. This is also known as the Unix Timestamp. PHP Date: strtotime() Using strtotime or mktime we can find exact dates or days.

PHP reference by Jan Zumwalt

Pg 26 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

There are two ways we can do that. 1. strtotime - Convert any English textual datetime description into a Unix timestamp. 2. mktime - Get Unix timestamp for a date. Find Yesterdays date
<?php echo "yesterday was ".date("Y-m-d", strtotime("-1 days")); ?>
Result: yesterday was 2010-03-18

Find Date one week ago


<?php echo "1 week from today was ".date("Y-m-d", strtotime("-1 weeks")); ?>
Result: 1 week from today was 2010-03-12

Find Date one month after


<?php echo "1 month from today will be ".date("Y-m-d", strtotime("+1 months")); ?>
Result: 1 month from today will be 2010-04-19

PHP Date: mktime() mktime is used to find more specific things like the next leap year. Find Leap Year
<?php $day = ""; /* * since leap year falls ever 4 years so loop for 4 times */ for($i=0; $i<4; $i++) { //get day timestamp for feburary 29 for this year $day = date("d", mktime(0, 0, 0, 2, 29, date("Y")+$i)); /* * check if day equals 29. * If day is 29 then it must be the leap year. if day is 01, then it not a leap year. */ if($day == 29) { $year = date("Y")+$i; break; } } echo "next leap year is in year $year"; ?>
Result: next leap year is in year 2012

PHP reference by Jan Zumwalt

Pg 27 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

The mktime takes 6 arguments. The parameters are explained as below. 1. 2. 3. 4. 5. 6.


hour minute second month day year

The The The The The The

number number number number number number

of of of of of of

the hour. the minute. seconds past the minute. the month. the day. year.

PHP reference by Jan Zumwalt

Pg 28 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

File IO
File functions
Function basename() chgrp() chmod() chown() clearstatcache() copy() delete() fclose() feof() fflush() fgetc() fgetcsv() fgets() fgetss() file() file_exists() file_get_contents() file_put_contents fileatime() filectime() filegroup() fileinode() filemtime() fileowner() fileperms() filesize() filetype() flock() fnmatch() fopen() fpassthru() fputcsv() fputs() fread() fscanf() fseek() fstat() ftell() ftruncate() fwrite() glob() is_executable() Description Returns the filename component of a path Changes the file group Changes the file mode Changes the file owner Clears the file status cache Copies a file See unlink() or unset() Closes an open file Tests for end-of-file on an open file Flushes buffered output to an open file Returns a character from an open file Parses a line from an open file, checking forCSV fields Returns a line from an open file Returns a line, with HTML and PHP tags removed, from an open file Reads a file into an array Checks whether a file exists Reads a file into a string Writes a string to a file Returns the last access time of a file Returns the last change time of a file Returns the group ID of a file Returns the inode number of a file Returns the last modification time of a file Returns the user ID (owner) of a file Returns the permissions of a file Returns the file size Returns the file type Locks or releases a file Matches a filename or string against a specified pattern Opens a file or URL Reads from an open file, until EOF, and writes the result to the output buffer Formats a line as CSV and writes it to an open file Alias of fwrite() Reads from an open file Parses input from an open file according to a specified format Seeks in an open file Returns information about an open file Returns the current position in an open file Truncates an open file to a specified length Writes to an open file Returns an array of filenames / directories matching a specified pattern Checks whether a file is executable

PHP reference by Jan Zumwalt

Pg 29 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

is_file() is_link() is_readable() is_uploaded_file() is_writable() is_writeable() link() linkinfo() lstat() mkdir() move_uploaded_file() parse_ini_file() pathinfo() pclose() popen() readfile() readlink() realpath() rename() rewind() rmdir() set_file_buffer() stat() symlink() tempnam() tmpfile() touch() umask() unlink()

Checks whether a file is a regular file Checks whether a file is a link Checks whether a file is readable Checks whether a file was uploaded via HTTP POST Checks whether a file is writeable Alias of is_writable() Creates a hard link Returns information about a hard link Returns information about a file or symbolic link Creates a directory Moves an uploaded file to a new location Parses a configuration file Returns information about a file path Closes a pipe opened by popen() Opens a pipe Reads a file and writes it to the output buffer Returns the target of a symbolic link Returns the absolute pathname Renames a file or directory Rewinds a file pointer Removes an empty directory Sets the buffer size of an open file Returns information about a file Creates a symbolic link Creates a unique temporary file Creates a unique temporary file Sets access and modification time of a file Changes file permissions for files Deletes a file

fopen ($filename, $mode);

Opening a file file modes


'r' 'r+' 'w' 'w+' 'a' 'a+' Open for reading only; place the file pointer at the beginning of the file. Open for reading and writing; place the file pointer at the beginning of the file. Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, it attempt to create it. Open for read/write; file pointer at beginning of file and truncate the file to zero length. If file does not exist, create it. Open for write only; file pointer at the end of the file. If file does not exist, create it. Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Example 1 open file for reading


<?php $fh = fopen("myfile.txt", "r"); if($fh==false) die("unable to create file");

PHP reference by Jan Zumwalt

Pg 30 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

?>
Result: This opens myfile.txt for reading and places the pointer at the beginning of the file.

What if file doesn't exist? If the myfile.txt doesn't exist, the file handle $fh will return false. If we need the file created if it doesn't exist, we can use the file mode 'a'. This will create a new file myfile.txt, if it doesn't already exists. Example 2 open file for reading and writing
<?php $fh = fopen(" myfile.txt", "r+"); if($fh==false) die("unable to create file"); ?>
Result: Opens myfile.txt for r/w, pointer at beginning of file.

is_file() Testing if file or dir exists


if(!is_file("myfile.txt")) die("Could not find the file."); if(!is_dir("somewhere/temp")) die("Could not find the directory.");

Open at end of file We can use the file mode 'a' and 'a+' respectively to read/write from the end of the file. fgets() Read Line In this section we will learn how to open and read files in PHP. The fgets() functions is used to read a line from a file. Using this function we either read the entire line into a string or specify the number characters we like to read. Lets looks at the function more closely...
fgets ($handle, $length);

The fgets() function has two parameters. The first parameter is the file pointer and the second parameter (which is optional) is the number of bytes to read in one call. If the second parameter is not given, the function will read at the end of the line.
$handle - the file pointer $length - number of bytes to read. If length is not specified it will read at the end of the line.

Now, let's look at some examples that show how to read from a file. Reading entire line The following code reads a line from a file into a string. The code will start off by placing the file pointer at the beginning of the file and then reading the first line in our file into a string.
<?php $fh = fopen("myfile.txt", "r"); $line = fgets($fh); echo $line;

PHP reference by Jan Zumwalt

Pg 31 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

fclose($fh); ?>

In the above code, we didn't specify how many bytes to read. Therefore, the entire line is read. Remember, the mode 'r' means we are opening the file for reading only. Reading number of bytes In this second example, we use the same method to read a given number of characters in a line.
<?php $fh = fopen("myfile.txt", "r"); $str = fgets($fh, 64); echo $str; $line2 = fgets($fh, 64); echo $str; fclose($fh); ?>

The above code reads the first 64 characters and then reads the next 64 characters in the line. Reading file line by line Using the fgets() function we can also read the entire file line by line in one loop. Let's look at two different examples that show how this is done. Example 1 reading file line by line
<?php $fh = fopen("myfile.txt", "r"); while(true) { $line = fgets($fh); if($line == null)break; echo $line; } fclose($fh); ?>

Example 2 reading file line by line


<?php $fh = fopen("myfile.txt", "r"); while (!feof($fh)) { $line = fgets($fh); echo $line; } fclose($fh); ?>

PHP reference by Jan Zumwalt

Pg 32 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

file_get_contents() read entire file In some cases we may need to read the entire file. Reading the file line by line can be tedious. We can utilize PHP functions that will read the entire file content into a single string. One such function is file_get_contents() Let's look at an example of how this function might be used.
<?php $fh = fopen("myfile.txt", "r"); $file = file_get_contents("myfile.txt"); echo $file; ?>

The above code will read the entire file content of myfile.txt into the string $file. Please note that if the file is fairly large, our script or application may hang due to lack of resources. It is not advisable to read big files at one time. Either we should split the file into two or more pieces or utilize more smart ways of reading the file. fwrite() writing to file Writing text to files is easy in PHP. We can usually use the fwrite() function. However, we must make sure to open the file as writable before writing. Let's examine the fwrite() function closely.
fwrite($handle, $string, $length);

The fwrite() function takes three arguments, the file handle, the string to be written and the number of bytes to be written, which is optional.
$handle $string $length

the file stream string to be written in file optional. Number of bytes to write in file.

Now, let's work with some examples below on how to write text to files. Write text to a file The first example demonstrates how to write a single line of text to a file.
<?php $handle = fopen("myfile.txt", 'w+'); if($handle) { if(!fwrite($handle, "Student Name: Mark Fendisen")) die("couldn't write to file."); echo "success writing to file"; } ?> <pre>

PHP reference by Jan Zumwalt

Pg 33 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

The above code creates a new file myfile.txt in writable mode using "w+" and writes "Student Name: Mark Fendisen" into the file. That was fairly easy, wasn't it? Note: "w+" truncates the file to zero, that is, deletes everything in the file before writing. If the file doesn't exist, it create a new file. Write at beginning of a file Using file open mode "a+", we can append text to either beginning or end of a file. The first example we tackle is, how to write text at the beginning of a file. We must first open the file in append mode using 'a+'. In other words, open an existing file so that we can add more stuff to it. The code below writes the string "Student ID: 12345" at the beginning without truncating the file, which means that anything already in the file is left alone, and the new string in written at the beginning of the file. When we open a file with mode 'a+', the file pointer is placed at the end of the file but remember we want to write at the beginning of the file. To move the file pointer back to the beginning for writing, we can use the function rewind() as shown below.
<?php $file_name= "myfile.txt"; if(file_exists($file_name)) { //open file for writng and place pointer at the end $handle = fopen($file_name, 'a+'); if(!$handle) { die("couldn't open file <i>$file_name</i>"); } //place pointer at the beginning of the file. rewind($handle); //write to file fwrite($handle, "Student ID: 12345"); echo "success writing to file"; } else { echo "file <i>$file_name</i> doesn't exists"; } fclose($handle); ?>

Write at end of a file As seen in the above example, the mode "a+" automatically places the file pointer at the end of the file so we don't have to do anything extra. The code below writes "Student GPA: 2.9" at the end of the file.
<?php $file_name= "myfile.txt";

PHP reference by Jan Zumwalt

Pg 34 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

if(file_exists($file_name)) { //open file for writng and place pointer at the end $handle = fopen($file_name, 'a+'); if(!$handle) { die("couldn't open file <i>$file_name</i>"); } fwrite($handle, "Student GPA: 2.9"); echo "success writing to file"; } else { echo "file <i>$file_name</i> doesn't exists"; } fclose($handle); ?>

Write string with line breaks The examples we have used so far write text in one straight line. What if we want line breaks? We can write text one line at a time by inserting an end of line command, '\n' or '\r'. If we are using a Window PC, use "\n". For Macintosh, use "\r". But just to be on the safe side, we can use both together like this "\r\n". Regardless of what system you're running our code on. This will guarantee it works under both PCs and Macintosh.
<?php $file_name = "myfile.txt"; if(file_exists($file_name)) { //open file for writng and place pointer at the end $handle = fopen($file_name, 'w'); if(!$handle) { die("couldn't open file <i>$file_name</i>"); } $str.= "Student Name: Mark Fendisen\r\n"; $str.= "Student ID: 12345\r\n"; $str.= "Student GPA: 2.9\r\n"; fwrite($handle, $str); echo "success writing to file"; } else { echo "file <i>$file_name</i> doesn't exists"; } fclose($handle); ?>

Simultaneous Read / Write Many times we need to read and write to a file at the same time. The example below shows how to parse data in a file. We will read the file line by line and overwrite small parts of the text with a new string. For our example below, assume we have a file with the following information about a student.

PHP reference by Jan Zumwalt

Pg 35 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Student Name: Mark Fendisen Student ID: 12345 Student GPA: 2.9

What we want to do is update his GPA from 2.9 from 3.1. How would we do it? First we need to open the file in both read and write mode using "r+". Next, we read the file line by line using fgets function until we reach the student gpa line. We then use the string replace function to replace 2.9 with 3.1 and write the new string back to the file. Let's look at an example.
<?php $file_name= "myfile.txt"; if(file_exists($file_name)) { /* Open file for both reading and writng. * Place pointer at the beginning of the file. */ $handle = fopen($file_name, 'r+'); if(!$handle) { die("couldn't open file <i>$file_name</i>"); } while(1) { //read line $line = fgets($handle); //if end of file reached then stop reading anymore if($line == null)break; //replace student gpa with new updated gpa if(preg_match("/Student GPA:/", $line)) { $new_line = str_replace("Student GPA: 2.9", "Student GPA: 3.1", $line); } else { //set file content to a string $str.= $line; } } //append new updated gpa to file content $str.= $new_line; //set pointer back to beginning rewind($handle); //delete everything in the file. ftruncate($handle, filesize($file_name)); //write everything back to file with the updated gpa line fwrite($handle, $str); echo "success writing to file"; } else { echo "file <i>$file_name</i> doesn't exists"; } fclose($handle); ?>

PHP reference by Jan Zumwalt

Pg 36 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Result: Student Name: Mark Fendisen Student ID: 12345 Student GPA: 3.1

The above code is fairly large. It might be wise to go over it slowly and read the internal comments in the code to understand how it is done.

Directory functions
Function chdir() chroot() closedir() dir() dir_exists() dirname() disk_free_space() disk_total_space() diskfreespace() file_exists() getcwd() glob() is_dir() link() linkinfo() lstat() mkdir() opendir() readdir() rename() rewinddir() rmdir() scandir() Description Changes the current directory Changes the root directory of the current process Closes a directory handle Opens a directory handle and returns an object Checks whether a dir exists Returns the directory name component of a path Returns the free space of a directory Returns the total size of a directory Alias of disk_free_space() Test whether a file or directory exists Returns the current directory Returns an array of filenames / directories matching a specified pattern Checks whether a file is a directory Creates a hard link Returns information about a hard link Returns information about a file or symbolic link Creates a directory Opens a directory handle Returns an entry from a directory handle Renames a file or directory Resets a directory handle Removes an empty directory Lists files and directories inside a specified path

PHP reference by Jan Zumwalt

Pg 37 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Remote File IO
fsockopen($hostname, $port, $errno, $errstr, $timeout); where: $hostname - location or URL of the file or page. $port - the default port is 80, unless otherwise told. $errno - optional, contains error number during connection. $errstr - optional. contains error message during connection $timeout - optional. seconds before connection timeout error.

Example 1 open remote files The example below shows how to read the source code of a page and display it.
<?php $fp = fsockopen("www.somedomain.com", 80, $errno, $errstr, 30); if ($fp == false) { echo "$errstr ($errno)"; } else { fputs($fp, "GET / HTTP/1.1\r\n"); fputs($fp, "Host: www.somedomain.com\r\n"); fputs($fp, "Connection: Close\r\n\r\n"); while (!feof($fp)) { echo fgets($fp, 1024); } fclose($fp); } ?>

PHP reference by Jan Zumwalt

Pg 38 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Forms
Useful form commands
echo echo echo echo echo echo echo echo $_SERVER['PHP_SELF'].'<br>'; # $_SERVER['SERVER_NAME'].'<br>'; # $_SERVER['DOCUMENT_ROOT'].'<br>'; $_SERVER['QUERY_STRING'].'<br>'; $_SERVER['SCRIPT_FILENAME'].'<br>'; $_SERVER['HTTP_REFERER'].'<br>'; $_SERVER['PHP_AUTH_USR'].'<br>'; $_SERVER['PHP_AUTH_PW'].'<br>'; /somepath/myfile.php localhost or www.example.com # C:/www/somedir or /var/www/somedir # ?greet=hello&pie=apple # C:/path/index.php # www.example.com/myscript.php # guest # rex245j

Processing a remote form is a two step process. First we must input the data and then it must be processed i.e. saved or displayed. Redirection and new windows
<?php /* Be sure that you do not have any text sent to the browser before this command, or it will not work. */ header( 'Location: http://www.yoursite.com/new_page.html' ) ;

?> Javascript echo '<script type="text/javascript">window.location="index.php"</script>';

Input form visitor_form.php


<html> <head><title>Simple php form visitor_form.php</title></head> <body> <?php print ' <form method="post" action="visitor_info.php">Your Name: <br /> <input type="text" name="visitorname" size="35" /> <br /><br /> Your Email:<br /> <input type="text" name="visitormail" size="35" /> <br /> <br /> Age:<br /> <select name="visitorage" size="1"> <option value="0-10">0-10</option> <option value="11-25">11-25</option> <option value="26-50">26-50</option> <option value="50+">over 50</option> </select> <br /><br /> <input type="submit" value="Send Info" /> <br /> </form> ' // end of print ?> </body> </html>

Process form visitor_info.php


<html>

PHP reference by Jan Zumwalt

Pg 39 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

<head> <head><title>Simple php form visitor_info.php</title></head> </head> <body> <h1> PHP simple form processing </h1> <?php $vname = $_POST['visitorname']; $vmail = $_POST['visitormail']; $vage = $_POST['visitorage']; $todayis = date("l, F j, Y, g:i a"); print "Today's date: $todayis<br />"; print "You name: $vname<br />"; print "Your email: $vmail<br />"; print "Your age: $vage<br />"; ?> <br /> <a href="visitor_form.php"> back to form </a> </body> </html>

Drop Down Box

html version
$drop box = '<select name="boxname">' . '<option value="1" >Lable1</option>' . '<option value="2" >Lable2</option>' . '</option>';

mysql version
$result = mysql_query("select * FROM mytable") or die(mysql_error()); print '<select name="boxname">\n'; while($row = mysql_fetch_array($result)) { print '<option value="' . $row['item'] . '">' . $row['name'] . "</option>\n"; } print '</option>\n';

Email
mail($to, $subject, $message, $headers);

where:
to subject message headers

the recipients email address the subject of the email. the email message to be sent. the header contains information such as the format of the email (plain text or HTML), senders name and email, reply to address, CC and BCC.

Sending Plain Text Email The following code will send out a plain text email using the PHP built in mail function.
<?php function send_email($from, $to, $cc, $bcc, $subject, $message){ $headers = "From: ".$from."\r\n"; $headers .= "Reply-To: ".$from."\r\n"; $headers .= "Return-Path: ".$from."\r\n";

PHP reference by Jan Zumwalt

Pg 40 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

$headers .= "CC: ".$cc."\r\n"; $headers .= "BCC: ".$to."\r\n"; if (mail($to,$subject,$message,$headers) ) { echo "email sent"; } else { echo "email could not be sent"; } } $subject = "Hello!"; $message = "Hello! How are we today?"; send_email("youraddress@domain.com", "recpeient@domain.com", "someone@domain.com", "hidden_email@domain.com", $subject , $message); ?>

In our send_email function we set the appropriate headers. Reply-To and Return-Path points to the email we want the recipient to reply to. Some server requires the use of Return-Path, so it's good to leave it in there. Next we call the send_email function which sends out the email. Sending HTML Email The following function will send out an HTML formatted email using the PHP built in mail function.
<?php function send_email($from, $to, $subject, $message){ $headers = "From: ".$from."\r\n"; $headers .= "Reply-To: ".$from."\r\n"; $headers .= "Return-Path: ".$from."\r\n"; $headers .= "Content-type: text/html\r\n"; if (mail($to,$subject,$message,$headers) ) { echo "email sent"; } else { echo "email couldn't be sent"; } } $subject = "Helloooo!"; $message .= "<html><body>"; $message .= "<b>Hey! How are we today?</b>"; $message .= "<br>Regards"; $message .= "</body></html>"; send_email("youraddress@domain.com", "recpeient@domain.com", $subject , $message); ?>

In our send_email function we set the content type headers to text/html. It is important to do this because it tells the email server that the email contains html code and to format and display the email correctly when it is opened. Remote input and processing Email This is an example of an email input form that is sent to a php file for processing. Input form email.php
<html> <head>

PHP reference by Jan Zumwalt

Pg 41 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Email Form </title> </head> <body> <form method="post" action="sendmail.php"> <!-- DO NOT change ANY of the php sections --> <?php $ipi = getenv("REMOTE_ADDR"); $httprefi = getenv ("HTTP_REFERER"); $httpagenti = getenv ("HTTP_USER_AGENT"); ?> <input type="hidden" name="ip" value="<?php echo $ipi ?>" /> <input type="hidden" name="httpref" value="<?php echo $httprefi ?>" /> <input type="hidden" name="httpagent" value="<?php echo $httpagenti ?>" /> Your Name: <br /> <input type="text" name="visitor" size="35" /> <br /> Your Email:<br /> <input type="text" name="visitormail" size="35" /> <br /> <br /> <br /> Attention:<br /> <select name="attn" size="1"> <option value=" Sales n Billing ">Sales n Billing </option> <option value=" General Support ">General Support </option> <option value=" Technical Support ">Technical Support </option> <option value=" Webmaster ">Webmaster </option> </select> <br /><br /> Mail Message: <br /> <textarea name="notes" rows="4" cols="40"></textarea> <br /><br /> <input type="submit" value="Send Mail" /> <br /> </form> </body> </html>

Processing program sendmail.php


<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Sendemail Script</title> </head> <body> <!-- Reminder: Add the link for the 'next page' (at the bottom) --> <!-- Reminder: Change 'YourEmail' to our real email --> <?php $ip = $_POST['ip']; $httpref = $_POST['httpref']; $httpagent = $_POST['httpagent']; $visitor = $_POST['visitor']; $visitormail = $_POST['visitormail']; $notes = $_POST['notes']; $attn = $_POST['attn'];

PHP reference by Jan Zumwalt

Pg 42 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

if (eregi('http:', $notes)) { die ("Do NOT try that! ! "); } if(!$visitormail == "" && (!strstr($visitormail,"@") || !strstr($visitormail,"."))) { echo "<h2>Use Back - Enter valid e-mail</h2>\n"; $badinput = "<h2>Feedback was NOT submitted</h2>\n"; echo $badinput; die ("Go back! ! "); } if(empty($visitor) || empty($visitormail) || empty($notes )) { echo "<h2>Use Back - fill in all fields</h2>\n"; die ("Use back! ! "); } $todayis = date("l, F j, Y, g:i a") ; $attn = $attn ; $subject = $attn; $notes = stripcslashes($notes); $message = " $todayis [EST] \n Attention: $attn \n Message: $notes \n From: $visitor ($visitormail)\n Additional Info : IP = $ip \n Browser Info: $httpagent \n Referral : $httpref \n "; $from = "From: $visitormail\r\n"; mail("YourEmail", $subject, $message, $from); ?> <p align="center"> Date: <?php echo $todayis ?> <br /> Thank we : <?php echo $visitor ?> ( <?php echo $visitormail ?> ) <br /> Attention: <?php echo $attn ?> <br /> Message:<br /> <?php $notesout = str_replace("\r", "<br/>", $notes); echo $notesout; ?> <br /> <?php echo $ip ?> <br /><br /> <a href="email.php"> Next Page </a> </p> </body> </html>

PHP reference by Jan Zumwalt

Pg 43 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Sessions
In PHP, information is stored in session variables. Now lets learn how we create a session. Before we can store any information in session variables, we must first start up the session using the session_start() function. See below.
<?php session_start(); ?> <html> <body> </body> </html>

When we start a session a unique session id (PHPSESSID) for each visitor/user is created. we can access the session id using the PHP predefined constant PHPSESSID. The above code starts a session for the user on the server, and assigns a session id for that user's session. Note: The session_start() function must appear BEFORE the <html> tag Storing information in a session To store information in a session variable, we must use the predefined session variable $_SESSION.
<?php session_start(); $_SESSION["username"] = "johny"; $_SESSION["color"] = "blue"; ?>

Retrieving stored session information Retrieving stored session information is really easy. The stored session information is always available to any page.
<?php session_start(); echo $_SESSION["username"]; echo "<br/>"; echo $_SESSION["color"]; ?>
Result: Johny blue

Destroying/deleting session information Remember sessions are destroyed automatically after the user leaves the website or closes the browser. If we wish to clear a session variable yourself, we can simple use the unset() function to clean the session variable.
<?php session_start(); unset($_SESSION["username"]); unset($_SESSION["color"]); ?>

To completely destroy all session variables at once, use the session_destroy() function.
<?php session_destroy();

PHP reference by Jan Zumwalt

Pg 44 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

?>

PHP reference by Jan Zumwalt

Pg 45 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Regex
Test for string occurrence:
preg_match("operators",text); or preg_match("operators",$text_var);

Replace string occurrence:


preg_replace("operators", replace string, text);

example:
echo $mytext = Hi world; $test = preg_replace(/Hello/, Hi world, $mytext); echo $test;

preg_match functions
Function preg_match() Description The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.

preg_match_all() The preg_match_all() function matches all occurrences of pattern in string. preg_replace() preg_split() preg_grep() preg_ quote() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters. The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern. The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern. Quote regular expression characters

Common regex operators


Operator . (period) ^ (caret) $ (dollar sign) A a \d \D \w [A-E] [^A-E] X? X* X+ X{n} X{n,m} (abc|def)+ Match any single character Match the empty string that occurs at the beginning of a line or string Match the empty string that occurs at the end of a line Match an uppercase letter A Match a lowercase letter a Match any single digit Match any single nondigit character Match any single alphanumeric character; a synonym is [:alnum:] Match any of uppercase A, B, C, D, or E Match any character except uppercase A, B, C, D, or E Match none or one capital letter X Match zero or more capital Xes Match one or more capital Xes Match exactly n capital Xes Match at least n and no more than m capital Xes; if you omit m, the expression tries to match at least n Xes Match a sequence of at least one abc and def; abc and def would match Purpose

PHP reference by Jan Zumwalt

Pg 46 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Examples
Example /hello/ /^hello/ /hello$/ /he.o/ /he?llo/ /hello+/ /he*llo/ /hello|world/ /(A-Z)/ /[abc]/ /abc{1}/ /abc{1,}/ /abc{2,4}/ Match hello Match hello at the start of a string. Possible matches are hello or helloworld, hello at the end of a string. any character between he and o. Possible matches are helo or heyo, llo or hello hello one or more times. hello or hellohello llo, hello or hehello either match the word hello or world Using it with the hyphen character, this pattern will match every uppercase character from A to Z. E.g. A, B, C any single character a, b or c precisely one c character after the characters ab. E.g. matches abc, one or more c character after the characters ab. E.g. matches abc or abcc between two and four c character after the characters ab. E.g. matches abcc, abccc or abcccc, Does not Match worldhello helloworld hello

hellooo It will

ab, bc abcc Matches abc

validate_url
function validate_url($url) { return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)? (/.*)?$|i', $url); }

PHP reference by Jan Zumwalt

Pg 47 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

validate_email
function validate_email($email_address) { if( !preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+ ([a-zA-Z0-9\._-]+)+$/", $email_address)) { return false; } return true; }

validate_zip
function validate_zip($zip_code) { return preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zip_code); }

Highlite word in text:


$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor"; $text = preg_replace("/b(regex)b/i", '<span style="background:#5fc9f6">1</span>', $text); echo $text;

get all images from web page:


$images = array(); preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media); unset($data); $data=preg_replace('/(img|src)("|'|="|=')(.*)/i',"$3",$media[0]); foreach($data as $url) { $info = pathinfo($url); if (isset($info['extension'])) { if (($info['extension'] == 'jpg') || ($info['extension'] == 'jpeg') || ($info['extension'] == 'gif') || ($info['extension'] == 'png')) array_push($images, $url); } }

remove_duplicate_word
function remove_duplicate_word($text) { return preg_replace("/s(w+s)1/i", "$1", $text); }

Replace smiley with image


$texte='A text with a smiley :-)'; echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);

PHP reference by Jan Zumwalt

Pg 48 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Cookies
A cookie is used to store data for long periods of time. We might wish to remember a users name or phone number. A Cookie is a small flat file which sits on users computer. Each time that user requests a page or goes to a webpage, all cookie information is sent along with it.
setcookie($name, $value, $expire, $path, $domain, $secure)

$name $value $expire $path

name of the cookie. Example: "username" value of the cookie. Example: "john" time (in UNIX timestamp) when the cookie will expire. Example: time()+"3600". Cookie is set to expire after one hour. path on the server where cookie will be available. For example, if the path is set to "/", the cookie will be available through out the whole site. If the cookie is set to say "/news/", the cookie will only be available under /news/ and all its sub-directories. If no path is given, cookie in created under the current directory. domain where cookie will be available. Instead of path we can use domain settings. For example, if the domain is set to ".yourdomian.com", the cookie will be available within the domain and all its sub-domains, example news.yourdomain.com. If the cookie is set say "www.yourdomian.com" the cookie will be available under all www sub-domains, example " www.yourdomian.com/news" true if cookie is being set over a secure "https" server, false otherwise, Default value is false.

$domain

$secure

<?php setcookie("username", "john", time()+3600); ?> <html> <body> </body> </html>

In this example, Cookie username is set with value john which is set to expire in one hour (be erased). The function time() retrieves the current timestamp. Appending 3600 seconds (one hour) to the current time to make the cookie to expire after one hour. Note: A cookie must be set before any HTML code as shown above. Creating a permanent cookie Lets create a cookie which is set to last for 1 year.
<?php setcookie("username", "john", time()+(60*60*24*365)); ?>

Retrieving a cookie Cookie information is retrieved using the predefined $_COOKIE array. The following will retrieve our username cookie value
<?php echo $_COOKIE["username"]; ?>
Result: john

PHP reference by Jan Zumwalt

Pg 49 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

To print the entire $_COOKIE array, we can do the following


<?php echo "<pre>"; print_r($_COOKIE); echo "</pre>"; ?>
Result: Array ( [username] => john )

Deleting a Cookie In order to delete cookies, we just set the cookie to expire in the past date. The following will delete our username cookie.
<?php setcookie("username", "john", time()-(60*60*24*365)); ?>

PHP reference by Jan Zumwalt

Pg 50 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Miscellaneous functions
Function connection_aborted() connection_status() connection_timeout() constant() define() defined() die() eval() exit() get_browser() highlight_file() highlight_string() ignore_user_abort() pack() php_check_syntax() php_strip_whitespace() show_source() sleep() time_nanosleep() time_sleep_until() uniqid() unpack() usleep() Description Checks whether the client has disconnected Returns the current connection status Deprecated in PHP 4.0.5 Returns the value of a constant Defines a constant Checks whether a constant exists Prints a message and exits the current script Evaluates a string as PHP code Prints a message and exits the current script Returns the capabilities of the user's browser Outputs a file with the PHP syntax highlighted Outputs a string with the PHP syntax highlighted Sets whether a remote client can abort the running of a script Packs data into a binary string Deprecated in PHP 5.0.5 Returns the source code of a file with PHP comments and whitespace removed Alias of highlight_file() Delays code execution for a number of seconds Delays code execution for a number of seconds and nanoseconds Delays code execution until a specified time Generates a unique ID Unpacks data from a binary string Delays code execution for a number of microseconds

PHP reference by Jan Zumwalt

Pg 51 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

MySql
mysql_affected_rows Get number of affected rows in previous MySQL operation mysql_client_encoding Returns the name of the character set mysql_close Close MySQL connection mysql_connect Open a connection to a MySQL Server mysql_create_db Create a MySQL database mysql_data_seek Move internal result pointer mysql_db_name Get result data mysql_db_query Send a MySQL query mysql_drop_db Drop (delete) a MySQL database mysql_errno Returns the numerical value of the error message from previous MySQL operation mysql_error Returns the text of the error message from previous MySQL operation mysql_escape_string Escapes a string for use in a mysql_query mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both mysql_fetch_assoc Fetch a result row as an associative array mysql_fetch_field Get column information from a result and return as an object mysql_fetch_lengths Get the length of each output in a result mysql_fetch_object Fetch a result row as an object mysql_fetch_row Get a result row as an enumerated array mysql_field_flags Get the flags associated with the specified field in a result mysql_field_len Returns the length of the specified field mysql_field_name Get the name of the specified field in a result mysql_field_seek Set result pointer to a specified field offset mysql_field_table Get name of the table the specified field is in mysql_field_type Get the type of the specified field in a result mysql_free_result Free result memory mysql_get_client_info Get MySQL client info mysql_get_host_info Get MySQL host info mysql_get_proto_info Get MySQL protocol info mysql_get_server_info Get MySQL server info mysql_info Get information about the most recent query mysql_insert_id Get the ID generated in the last query mysql_list_dbs List databases available on a MySQL server mysql_list_fields List MySQL table fields mysql_list_processes List MySQL processes mysql_list_tables List tables in a MySQL database mysql_num_fields Get number of fields in result mysql_num_rows Get number of rows in result mysql_pconnect Open a persistent connection to a MySQL server mysql_ping Ping a server connection or reconnect if there is no connection mysql_query Send a MySQL query mysql_real_escape_string Escapes special characters in a string for use in a SQL statement mysql_result Get result data mysql_select_db Select a MySQL database mysql_set_charset Sets the client character set mysql_stat Get current system status mysql_tablename Get table name of field mysql_thread_id Return the current thread ID mysql_unbuffered_query Send SQL query to MySQL w/out fetching and buffering the result rows.

PHP reference by Jan Zumwalt

Pg 52 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

<?php /* +-------------------------------------------------------------------+ | | | File: php_mysql_test.php Version: 2012-02-04 | | | | Purpose: shows syntax for most common mysql operations | | using improved mysql"i" | | | +-------------------------------------------------------------------+

*/

// <---------maintenance support ----------> $debug = 'false'; if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/include/debug.php')) { include($_SERVER['DOCUMENT_ROOT'] . '/include/debug.php'); } error_reporting(E_ALL ^ E_NOTICE); ini_set('display_errors', 'on'); // detect all errors // display all errors

// <---------start html ----------> if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/css/admin.css')) { echo '<html><head>'; include($_SERVER['DOCUMENT_ROOT'] . '/css/admin.css'); echo '</head><body>'; }else{ echo '<html> <head> <style> body { font-family: courier; /* background-color: #500; /* dark red */ background-color: #002; /* midnight blue */ color: #ddd; margin-left: 100; margin-right: 100; margin-top: 50; margin-bottom: 50; } </style> </head> <body>'; } // <---------db connect ----------> $db = mysqli_connect("localhost","root","") or die(mysqli_error()); // <---------delete db ----------> $sql_delete_db = 'DROP DATABASE IF EXISTS `test_db` '; $result = mysqli_query($db, $sql_delete_db) or die(mysqli_error()); // <---------create db ----------> $sql_create_db = 'CREATE DATABASE IF NOT EXISTS `test_db`'; mysqli_query($db, $sql_create_db) or die(mysqli_error()); // <---------connect to db ----------> $result = mysqli_select_db($db,"test_db") or die(mysqli_error()); // <---------delete table ----------> $sql_delete_db = 'DROP TABLE IF EXISTS `people` '; $result = mysqli_query($db, $sql_delete_db) or die(mysqli_error()); // <---------create table ----------> $sql_maketbl = "CREATE TABLE `test_db`.`people`(

PHP reference by Jan Zumwalt

Pg 53 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(25) COMMENT 'first name', age INT(3) COMMENT 'yrs', updated TIMESTAMP COMMENT 'last update', update_by VARCHAR(25) NOT NULL DEFAULT 'unknown' COMMENT 'user name', note VARCHAR(255) DEFAULT 'na' )"; $result = mysqli_query($db, $sql_maketbl) or die(mysqli_error()); // <---------add record ----------> $sql_add_data = "INSERT INTO `test_db`.`people` (`id`, `name`, `age`, `updated`, `update_by`, `note`) VALUES (NULL, 'Mickey Mouse', '50', CURRENT_TIMESTAMP, 'janz' , 'na'), (NULL, 'Mini Mouse' , '50', CURRENT_TIMESTAMP, 'janz' , 'na'), (NULL, 'Daffy' , '51', CURRENT_TIMESTAMP, 'unknown', 'na')"; $result = mysqli_query($db, $sql_add_data) or die(mysqli_error()); // <---------count result rows ----------> $sql_update = "SELECT * FROM `test_db`.`people` WHERE name LIKE 'M%' "; $result = mysqli_query($db, $sql_update) or die(mysqli_error()); $cnt = mysqli_num_rows($result); echo "There are $cnt records with names starting with 'M'.<br>"; // <---------update record ----------> $sql_update = "UPDATE `test_db`.`people` SET `age` = '36' WHERE `name` LIKE '%Mini%' "; $result = mysqli_query($db, $sql_update) or die(mysqli_error()); // <---------delete record ----------> $sql_update = "DELETE FROM `test_db`.`people` WHERE `name` LIKE '%Daffy%' "; $result = mysqli_query($db, $sql_update) or die(mysqli_error()); // <---------show table data ----------> $sql_update = "SELECT * FROM `test_db`.`people` "; $result = mysqli_query($db, $sql_update) or die(mysqli_error()); echo "<pre>"; while($row = mysqli_fetch_assoc($result)) { echo print_r($row); } echo "</pre>"; // <---------table structure (html) ---------> $database = "test_db"; $result = mysqli_select_db($db,$database) or die(mysqli_error()); $loop = mysqli_query($db, "SHOW TABLES FROM $database") or die('SHOW TABLES: cannot select tables'); // $tborder = '#bb4400'; $strip1 = '#994400'; $strip2 = '#aa6622'; // orange table theme $tborder = '#334499'; $strip1 = '#3388bb'; $strip2 = '#2266aa'; // blue table theme while($table = mysqli_fetch_array( $loop)) { echo "<br> <table cellpadding='2' cellspacing='2' border='0' width='75%'> <tr bgcolor=$tborder> <td colspan='6' align='center'><b><font size='+3' color='#FFFFFF'>" . $table[0] . " </font><br/></b>table structure</td> </tr> <tr bgcolor=$tborder> <td ALIGN='center'>Field</td> <td ALIGN='center'>Type : Length</td> <td ALIGN='center'>Key</td>

PHP reference by Jan Zumwalt

Pg 54 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

<td ALIGN='center'>Index</td> <td ALIGN='center'>Default</td> <td ALIGN='center'>Extra</td> </tr>"; $i = 0; //row counter $row = mysqli_query($db, "SHOW columns FROM " . $table[0]) or die ('cannot select table fields'); while ($col = mysqli_fetch_array($row)) { echo "<tr"; if ($i % 2 == 0) { echo " bgcolor=$strip1 "; }else{ echo " bgcolor=$strip2 "; } echo "> <td bgcolor=$tborder>" . $col[0] . "</td> <td>" . $col[1] . "</td> <td>" . $col[2] . "</td> <td>" . $col[3] . "</td> <td>" . $col[4] . "</td> <td>" . $col[5] . "</td> </tr>"; $i++; } //end row loop echo "</table><br/>"; } //end table loop echo "<br/>"; // <---------table structure (text) ---------> $sql_list_tables = "DESCRIBE `people` "; $result = mysqli_query($db, $sql_list_tables) or die(mysqli_error()); while($row = mysqli_fetch_assoc($result)) { $str = implode(",",$row); echo $str . "<br>"; } echo "<br>"; // <---------show table syntax ---------> $sql_list_tables = "SHOW CREATE TABLE `people` "; $result = mysqli_query($db, $sql_list_tables) or die(mysqli_error()); echo "<br/><pre>"; while($row = mysqli_fetch_assoc($result)) { echo print_r($row) . "<br>"; } echo "</pre><br/>"; // <---------close mysql connection ---------> mysqli_close($db); echo 'Mysql connection closed, end of program.'; echo " </BODY> </HTML>"; ?>

PHP reference by Jan Zumwalt

Pg 55 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Output
There are 2 records with names starting with 'M'. Array ( [id] => 1 [name] => Mickey Mouse [age] => 50 [updated] => 2012-02-06 22:09:52 [update_by] => janz [note] => na ) 1Array ( [id] => 2 [name] => Mini Mouse [age] => 36 [updated] => 2012-02-06 22:09:52 [update_by] => janz [note] => na ) 1 people table structure Field id name age updated Type : Length int(11) varchar(25) int(3) timestamp Key Index NO YES YES NO NO CURRENT_TIMESTAMP unknown na on update CURRENT_TIMESTAMP PRI Default Extra auto_increment

update_by varchar(25) note

varchar(255) YES

id,int(11),NO,PRI,,auto_increment name,varchar(25),YES,,, age,int(3),YES,,, updated,timestamp,NO,,CURRENT_TIMESTAMP,on update CURRENT_TIMESTAMP update_by,varchar(25),NO,,unknown, note,varchar(255),YES,,na,


Array ( [Table] => people [Create Table] => CREATE TABLE `people` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(25) DEFAULT NULL COMMENT 'first name', `age` int(3) DEFAULT NULL COMMENT 'yrs', `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'last update', `update_by` varchar(25) NOT NULL DEFAULT 'unknown' COMMENT 'user name', `note` varchar(255) DEFAULT 'na', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 ) 1

Mysql connection closed, end of program.

PHP reference by Jan Zumwalt

Pg 56 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Security

Without security measures it is easy for someone to access data on our server, or even make changes to the database. This can occur if the user sets a variable to a value which edits the SQL string being generated. Further reading should be done on this subject. There are many websites which give full details (search for 'sql injection attack'). This security hole is easy to plug. Always check input data for invalid characters and use PHP's built in functions to remove control characters and HTML code etc.

mysql_real_escape_string will take a regular string and sanitize it for you. htmlspecialchars converts reserved HTML characters (like <script> becomes &lt;script&gt;)

If you use the two functions together your database will be protected and youll safeguard your app against cross-site scripting (XSS) attacks when rendering user-submitted HTML (such as those posted in comments or forum threads). Unix File Permissions

If Mysql does not run properly on a Unix server, we may need to use the unix CHMOD command to set the permissions to 644. Database Construction MySQL databases have a standard setup. They are made up of a database which contains tables. Each of these tables is separate and can have different fields etc., even though it is part of one database. Each table contains records which are made up of fields. Field Types There are a wide variety of fields and attributes available in MySQL and I will cover a few of these here:
Field Type TINYINT SMALLINT MEDIUMINT INT VARCHAR TEXT Description Small Integer Number Small Integer Number Integer Number Integer Number Text (maximum 256 characters) Text

These are just a few of the fields which are available. We might wonder why we used VARCHAR fields for the a phone or fax number even though they are made up of digits. We could use INT fields but most programmers prefer to use VARCHAR because it allows dashes and spaces in the number, as well as textual numbers (like 1800-COMPANY). Primary Field

Every table needs a unique way of finding each record. It is customary to assign the first field as id. This field is set as PRIMARY, INDEX, UNIQUE and auto_increment (found under Extra in PHPMyAdmin). The auto increment setting means that when a record is added a new incremented unique ID number is automatically assigned.

PHP reference by Jan Zumwalt

Pg 57 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

HTML Input Inputting data using HTML pages is almost identical to inserting. The benefit, though, is that we do not need to change the script for each piece of data, and we can also allow our users to input their own data. The following code will show an HTML page with textboxes for entering data:
<form action="insert.php" method="post"> First Name: <input type="text" name="first"><br> Last Name: <input type="text" name="last"><br> Phone: <input type="text" name="phone"><br> Mobile: <input type="text" name="mobile"><br> Fax: <input type="text" name="fax"><br> E-mail: <input type="text" name="email"><br> Web: <input type="text" name="web"><br> <input type="Submit"> </form>

The example form is simple for learning purposes but could be formatted and have other changes made to it. The form passes the users data as variables. The next section of code passes the forms variables ($_POST) into PHP variables to be processed.
<?php $username="username"; $password="password"; $database="your_database"; $first=$_POST['first']; $last=$_POST['last']; $phone=$_POST['phone']; $mobile=$_POST['mobile']; $fax=$_POST['fax']; $email=$_POST['email']; $web=$_POST['web']; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query = "INSERT INTO contacts VALUES ('','$first','$last','$phone','$mobile','$fax','$email','$web')"; mysql_query($query); mysql_close(); ?>

HTML Output We can now write a full script to output the data. To keep things simple, this script makes no attempt to format the output:
<?php $username="username"; $password="password"; $database="your_database"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM contacts"; $result=mysql_query($query);

PHP reference by Jan Zumwalt

Pg 58 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

$num=mysql_numrows($result); mysql_close(); echo "<b><center>Database Output</center></b><br><br>"; $i=0; while ($i < $num) { $first=mysql_result($result,$i,"first"); $last=mysql_result($result,$i,"last"); $phone=mysql_result($result,$i,"phone"); $mobile=mysql_result($result,$i,"mobile"); $fax=mysql_result($result,$i,"fax"); $email=mysql_result($result,$i,"email"); $web=mysql_result($result,$i,"web"); echo "<b>$first $last</b><br> Phone: $phone<br> Mobile: $mobile<br> Fax: $fax<br> E-mail: $email<br> Web: $web<br> <hr><br>"; $i++; } ?>

Error Trapping It is quite unlikely that there will be no data, but if updating and deleting of records is allowed, it is certainly a possibility. Luckily, with PHP and MySQL, there is an easy way to prevent an error.
$num=mysql_numrows($result);

where $result contains the result of a query on the database (like selecting all the records). This will set the value of $num as the number of rows in the result (and it was used in a loop in part 4). Because of this we can make a simple error trap using an IF statement:
if ($num==0) { echo "The database contains no contacts yet"; } else { Loop... Code to show data... ...End of loop }

This can have many improvements added such as making it more user friendly (for example by providing a link to the Add Data page if no contacts exist). Limiting the Number of rows Keeping track of the number of rows can be used to print out only the last 5 records added to a database. The data would be sorted according to the id field (the one with the latest ID would be last). The last five rows of the sorted list are selected.

Here is an example:
if ($num>5) { $to=5; }else{

PHP reference by Jan Zumwalt

Pg 59 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

$to=$num; } $i=0; while ($i < $to) { REST OF CODE

This code would check if there were more than 5 rows in the database. If there were, the loop would be set to run 5 times. If there were less than 5 rows the loop would run the correct number of times to output the whole database. Selecting A Single Record In the last section we learned how to select records from the database based on the contents of particular fields using:
SELECT * FROM contacts WHERE field='value'

Now, by using the unique ID field we can select any record from our database using:
SELECT * FROM contacts WHERE id='$id'

Where $id is a variable holding a number of a record. This may seem trivial, but it can be used in a number of different ways. For example, if we wanted to have a dynamically generated site run through a database and a single PHP script, we could write the script to include the database data into the design. Then, using the id field, we could select each individual page and put it into the output. We can even use the page's URL to specify the record we want e.g.
http://www.yoursite.com/news/items.php?item=7393

Now the PHP script looks up the record with the id corresponding to $item, which in this case would be page 7393.

PHP reference by Jan Zumwalt

Pg 60 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

PHP reference by Jan Zumwalt

Pg 61 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

PHP reference by Jan Zumwalt

Pg 62 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

PHP reference by Jan Zumwalt

Pg 63 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Notes: _______________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________

PHP reference by Jan Zumwalt

Pg 64 of 65 Copyright 1995-2012

NeatInfo.com February 10, 2012

Notes: _______________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________
PHP reference by Jan Zumwalt Pg 65 of 65 Copyright 1995-2012 NeatInfo.com February 10, 2012