View
105
Download
1
Category
Tags:
Preview:
DESCRIPTION
A developers reference for using PHP. Includes simple MySql examples. Most topics include a short 5 to 10 line program that demonstrates a concept.
Citation preview
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 1 of 65
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 2 of 65
Blank Page
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 3 of 65
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 Yesterday’s 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 4 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 5 of 65
PHP Syntax <html> <title>my php page </ title> <body> <h1>PHP Test </ H1> <?php // Single line comment / * * multi-line * comment * / echo "hello there!" ; echo "<b> hello there! </ b>"; echo " <font color ='green' >hello there! </ font>"; echo "today is ".date('Y-m-d'); ?> </ body> </ html>
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 & Va ribles</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</spa n></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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 6 of 65
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 ; // another variable with a integer value echo $num . " – " ; // using echo to print the $num variable echo $str ; // reuse the $str variable to print its value echo $num; // 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 7 of 65
$_SERVER variables
'PHP_SELF' “/test.php/index.php” The filename of executing script relative to document root.
'argv' Array of arguments passed to the script. Command line gives C-style parameters. GET method returns query string.
'argc' Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE' “CGI/1.1”
What revision of the CGI specification the server is using.
'SERVER_ADDR' The IP address of the server under which the current script is executing.
'SERVER_NAME' server host name
'SERVER_SOFTWARE' Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL' “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' The timestamp of the start of request.
'REQUEST_TIME_FLOAT' The timestamp with microsecond of the start of request,
'QUERY_STRING' The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT' Document root directory of current script.
'HTTP_ACCEPT' Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET' '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' Contents of the Host: header, if there is one.
'HTTP_REFERER' Address of calling page (often not provided).
'HTTP_USER_AGENT' 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.
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 8 of 65
'REMOTE_ADDR' The IP address from which the user is viewing the current page.
'REMOTE_HOST' 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.
'REMOTE_PORT' User machine port used to communicate with web server.
'REMOTE_USER' The authenticated user.
'REDIRECT_REMOTE_USER' The authenticated user if the request is internally redirected.
'SCRIPT_FILENAME' The absolute pathname of the currently executing script.
'SERVER_ADMIN' 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.
'SERVER_PORT' '80'
Server machine port used for web server for communication.
'SERVER_SIGNATURE' Server version and virtual host name.
'PATH_TRANSLATED' Filesystem- (not document root-) based path to the current script,
'SCRIPT_NAME' Current script's path.
'REQUEST_URI' The URI which was given in order to access this page; for instance, '/index.html'.
'PHP_AUTH_DIGEST' 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).
'PHP_AUTH_USER' When doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW' When doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE' When doing HTTP authenticated this variable is set to the authentication type.
'PATH_INFO' 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.
'ORIG_PATH_INFO' Original version of 'PATH_INFO' before processed by PHP.
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 9 of 65
Array functions Function Description
array() Creates an array
array_change_key_case() Returns an array with all keys in lowercase or uppe rcase
array_chunk() Splits an array into chunks of arrays
array_combine() Creates an array by using one array for keys and an other for its values
array_count_values() Returns an array with the number of occurrences for each value
array_diff() Compares array values, and returns the differences
array_diff_assoc() Compares array keys and values, and returns the dif ferences
array_diff_key() Compares array keys, and returns the differences
array_diff_uassoc() Compares array keys and values, with an additional user-made function check, and returns the differences
array_diff_ukey() Compares array keys, with an additional user-made f unction check, and returns the differences
array_fill() Fills an array with values
array_filter() Filters elements of an array using a user-made func tion
array_flip() Exchanges all keys with their associated values in an array
array_intersect() Compares array values, and returns the matches
array_intersect_assoc() Compares array keys and values, and returns the mat ches
array_intersect_key() Compares array keys, and returns the matches
array_intersect_uassoc() Compares array keys and values, with an additional user-made function check, and returns the matches
array_intersect_ukey() Compares array keys, with an additional user-made f unction check, and returns the matches
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made functio n, which returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a specifi ed value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and return s the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
array_udiff() Compares array values in a user-made function and r eturns an array
array_udiff_assoc() Compares array keys, and compares array values in a user-made
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 10 of 65
function, and returns an array
array_udiff_uassoc() Compares array keys and array values in user-made f unctions, and returns an array
array_uintersect() Compares array values in a user-made function and r eturns an array
array_uintersect_assoc() Compares array keys, and compares array values in a user-made function, and returns an array
array_uintersect_uassoc() Compares array keys and array values in user-made f unctions, and returns an array
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of an ar ray
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an array
array_walk_recursive() Applies a user function recursively to every member of an array
arsort() Sorts an array in reverse order and maintain index association
asort() Sorts an array and maintain index association
compact() Create array containing variables and their values
count() Counts elements in an array, or properties in an ob ject
current() Returns the current element in an array
each() Returns the current key and value pair from an arra y
end() Sets the internal pointer of an array to its last e lement
extract() Imports variables into the current symbol table fro m an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an array by key in reverse order
ksort() Sorts an array by key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive "natural or der" algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an array in reverse order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an array
uasort() Sorts an array with a user-defined function and mai ntain index association
uksort() Sorts an array by keys using a user-defined functio n
usort() Sorts an array by values using a user-defined funct ion
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 11 of 65
Array constants Constant Description
CASE_LOWER Used with array_change_key_case() to convert array keys to lower case
CASE_UPPER Used with array_change_key_case() to convert array keys to upper case
SORT_ASC Used with array_multisort() to sort in ascending order
SORT_DESC Used with array_multisort() to sort in descending order
SORT_REGULAR Used to compare items normally
SORT_NUMERIC Used to compare items numerically
SORT_STRING Used to compare items as strings
SORT_LOCALE_STRING Used to compare items as strings, based on the current locale
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
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 12 of 65
null, ”” , ’’ , empty( ), and special values gettype() empty() is_null() isSet() (bool)
$x = ""; string true false true false
$x = null; NULL true true false false
var $x; (not set) NULL true true false false
$x = array(); array true false true false
$x = false; boolean true false true false
$x = 15; integer false false true true
$x = 1; integer false false true true
$x = 0; integer true false true false
$x = -1; integer false false true true
$x = "15"; string false false true true
$x = "1"; string false false true true
$x = "0"; string true false true false
$x = "-1"; string false false true true
$x = "foo"; string false false true true
$x = "true"; string false false true true
$x = "false"; string false false true true
Note: empty() and isSet() don't give warnings when the variables have not been previously defined.
comparison with == true false 1 0 -1 "1" "0" "-1" "1.3" "1.30" 1.3 1.30 array() "foo" ""
true true false true false true true false true true true true true false true false
false false true false true false false true false false false false false true false true
1 true false true false false true false false false false false false false false false
0 false true false true false false true false false false false false false true true
-1 true false false false true false false true false false false false false false false
"1" true false true false false true false false false false false false false false false
"0" false true false true false false true false false false false false false false false
"-1" true false false false true false false true false false false false false false false
"1.3" true false false false false false false false true true true true false false false
"1.30" true false false false false false false false true true true true false false false
1.3 true false false false false false false false true true true true false false false
1.30 true false false false false false false false true true true true false false false
array() false true false false false false false false false false false false true false false
"foo" true false false true false false false false false false false false false true false
"" false true false true false false false false false false false false false false true
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 13 of 65
comparison with === true false 1 0 -1 "1" "0" "-1" "1.3" "1.30" 1.3 1.30 array() "foo" ""
true true 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
1 false false true false false false false false false false false false false false false
0 false false false true false false false false false false false false false false false
-1 false false false false true false false false false false false false false false false
"1" false false false false false true false false false false false false false false false
"0" false false false false false false true false false false false false false false false
"-1" false false false false false false false true false false false false false false false
"1.3" false false false false false false false false true false false false false false false
"1.30" false false false false false false false false false true false false false false false
1.3 false false false false false false false false false false true true false false false
1.30 false false false false false false false false false false true true false false false
array() false false false false false false false false false false false false true false false
"foo" 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 true
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 14 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 15 of 65
� 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 16 of 65
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 it’s 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_nam e">' ; ?>
or
<?php print ' <center><h1>Important</h1></center> <p>This is a lot of html code<br />
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 17 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 18 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 19 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 20 of 65
//Give what day of the week it is. Returns Sunday t hrough 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 21 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 22 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 23 of 65
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. Let’s 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 "The first employee's name is ".$employee_name s[0]; echo "<br>"; echo "The second employee's name is ".$employee_nam es[1]; echo "<br>"; echo "The third employee's name is ".$employee_name s[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_n ames[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) sy ntax <?php $employee_names = array("Dana" => "Owner", "Matt" = > "Manager", "Susan" => "Cashier");
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 24 of 65
echo "Matt is the ".$employee_names["Matt"]; ?>
Result: Matt is the Manger
Multidimensional Arrays
Let’s 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. Let’s 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 25 of 65
"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(). Let’s 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 26 of 65
Date & Time
Calendar functions
Function Description
cal_days_in_month() Returns the number of days in a month for a specified year and calendar
cal_from_jd() Converts a Julian day count into a date of a specified calendar
cal_info() Returns information about a given calendar
cal_to_jd() Converts a date to Julian day count
easter_date() Returns the Unix timestamp for midnight on Easter of a specified year
easter_days() Returns the number of days after March 21, on which Easter falls for a specified year
FrenchToJD() Converts a French Republican date to a Julian day count
GregorianToJD() Converts a Gregorian date to a Julian day count
JDDayOfWeek() Returns the day of a week
JDMonthName() Returns a month name
JDToFrench() Converts a Julian day count to a French Republican date
JDToGregorian() Converts a Julian day count to a Gregorian date
jdtojewish() Converts a Julian day count to a Jewish date
JDToJulian() Converts a Julian day count to a Julian date
jdtounix() Converts a Julian day count to a Unix timestamp
JewishToJD() Converts a Jewish date to a Julian day count
JulianToJD() Converts a Julian date to a Julian day count
unixtojd() Converts a Unix timestamp to a Julian day count
PHP Date Function Syntax
date(format[, timestamp]) <?php echo date("Y-m-d"); // 2010-03-19 echo date("Y/m/d"); // 2010-03-19 echo date("M d, Y"); // Mar 19, 2010 echo date("F d, Y"); // March 19, 2010 echo date("D M d, Y"); // Fri Mar 19, 2010 echo date("l F d, Y"); // Friday March 19, 2010 echo date("l F d, Y, h:i:s"); // Friday March 19, 2010, 04:20:36 echo date("l F d, Y, h:i A"); // 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 27 of 65
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 Yesterday’s 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 28 of 65
The mktime takes 6 arguments. The parameters are explained as below.
1. hour - The number of the hour. 2. minute - The number of the minute. 3. second - The number of seconds past the minute. 4. month - The number of the month. 5. day - The number of the day. 6. year - The number of year.
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 29 of 65
File IO
File functions
Function Description
basename() Returns the filename component of a path
chgrp() Changes the file group
chmod() Changes the file mode
chown() Changes the file owner
clearstatcache() Clears the file status cache
copy() Copies a file
delete() See unlink() or unset()
fclose() Closes an open file
feof() Tests for end-of-file on an open file
fflush() Flushes buffered output to an open file
fgetc() Returns a character from an open file
fgetcsv() Parses a line from an open file, checking forCSV fields
fgets() Returns a line from an open file
fgetss() Returns a line, with HTML and PHP tags removed, from an open file
file() Reads a file into an array
file_exists() Checks whether a file exists
file_get_contents() Reads a file into a string
file_put_contents Writes a string to a file
fileatime() Returns the last access time of a file
filectime() Returns the last change time of a file
filegroup() Returns the group ID of a file
fileinode() Returns the inode number of a file
filemtime() Returns the last modification time of a file
fileowner() Returns the user ID (owner) of a file
fileperms() Returns the permissions of a file
filesize() Returns the file size
filetype() Returns the file type
flock() Locks or releases a file
fnmatch() Matches a filename or string against a specified pattern
fopen() Opens a file or URL
fpassthru() Reads from an open file, until EOF, and writes the result to the output buffer
fputcsv() Formats a line as CSV and writes it to an open file
fputs() Alias of fwrite()
fread() Reads from an open file
fscanf() Parses input from an open file according to a specified format
fseek() Seeks in an open file
fstat() Returns information about an open file
ftell() Returns the current position in an open file
ftruncate() Truncates an open file to a specified length
fwrite() Writes to an open file
glob() Returns an array of filenames / directories matching a specified pattern
is_executable() Checks whether a file is executable
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 30 of 65
is_file() Checks whether a file is a regular file
is_link() Checks whether a file is a link
is_readable() Checks whether a file is readable
is_uploaded_file() Checks whether a file was uploaded via HTTP POST
is_writable() Checks whether a file is writeable
is_writeable() Alias of is_writable()
link() Creates a hard link
linkinfo() Returns information about a hard link
lstat() Returns information about a file or symbolic link
mkdir() Creates a directory
move_uploaded_file() Moves an uploaded file to a new location
parse_ini_file() Parses a configuration file
pathinfo() Returns information about a file path
pclose() Closes a pipe opened by popen()
popen() Opens a pipe
readfile() Reads a file and writes it to the output buffer
readlink() Returns the target of a symbolic link
realpath() Returns the absolute pathname
rename() Renames a file or directory
rewind() Rewinds a file pointer
rmdir() Removes an empty directory
set_file_buffer() Sets the buffer size of an open file
stat() Returns information about a file
symlink() Creates a symbolic link
tempnam() Creates a unique temporary file
tmpfile() Creates a unique temporary file
touch() Sets access and modification time of a file
umask() Changes file permissions for files
unlink() Deletes a file
fopen ($filename, $mode);
Opening a file – file modes
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' 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.
'w+' Open for read/write; file pointer at beginning of file and truncate the file to zero length. If file does not exist, create it.
'a' Open for write only; file pointer at the end of the file. If file does not exist, create it.
'a+' 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 31 of 65
?>
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 t he 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. Let’s 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 32 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 33 of 65
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 – the file stream • $string – string to be written in file • $length – 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 34 of 65
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 en d $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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 35 of 65
if(file_exists($file_name)) { //open file for writng and place pointer at the en d $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 en d $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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 36 of 65
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 anymor e 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", "Stu dent 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 g pa 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 37 of 65
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 Description
chdir() Changes the current directory
chroot() Changes the root directory of the current process
closedir() Closes a directory handle
dir() Opens a directory handle and returns an object
dir_exists() Checks whether a dir exists
dirname() Returns the directory name component of a path
disk_free_space() Returns the free space of a directory
disk_total_space() Returns the total size of a directory
diskfreespace() Alias of disk_free_space()
file_exists() Test whether a file or directory exists
getcwd() Returns the current directory
glob() Returns an array of filenames / directories matching a specified pattern
is_dir() Checks whether a file is a directory
link() Creates a hard link
linkinfo() Returns information about a hard link
lstat() Returns information about a file or symbolic link
mkdir() Creates a directory
opendir() Opens a directory handle
readdir() Returns an entry from a directory handle
rename() Renames a file or directory
rewinddir() Resets a directory handle
rmdir() Removes an empty directory
scandir() Lists files and directories inside a specified path
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 38 of 65
Remote File IO
fsockopen($hostname, $port, $errno, $errstr, $timeo ut);
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 durin g connection $timeout - optional. seconds before connection t imeout 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 39 of 65
Forms
Useful form commands
echo $_SERVER['PHP_SELF'].'<br>'; # /somepath/my file.php echo $_SERVER['SERVER_NAME'].'<br>'; # localhost or www.example.com echo $_SERVER['DOCUMENT_ROOT'].'<br>'; # C:/www/s omedir or /var/www/somedir echo $_SERVER['QUERY_STRING'].'<br>'; # ?greet=he llo&pie=apple echo $_SERVER['SCRIPT_FILENAME'].'<br>'; # C:/path/ index.php echo $_SERVER['HTTP_REFERER'].'<br>'; # www.exam ple.com/myscript.php echo $_SERVER['PHP_AUTH_USR'].'<br>'; # guest echo $_SERVER['PHP_AUTH_PW'].'<br>'; # 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 t o the browser before this command, or it will not work. */ header( 'Location: http://www.yoursite.com/new_p age.html' ) ; ?> Javascript echo '<script type="text/javascript">window.locat ion="index.php"</script>';
Input form – visitor_form.php
<html> <head><title>Simple php form visitor_form.php</titl e></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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 40 of 65
<head> <head><title>Simple php form visitor_info.php</titl e></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 d ie(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';
mail($to, $subject, $message, $headers);
where:
to - the recipients email address
subject - the subject of the email.
message - the email message to be sent.
headers - the header contains information such as the forma t 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 41 of 65
$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@dom ain.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@dom ain.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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 42 of 65
<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 $i pi ?>" /> <input type="hidden" name="httpref" value="<?php ec ho $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 Billin g </option> <option value=" General Support ">General Suppor t </option> <option value=" Technical Support ">Technical Su pport </option> <option value=" Webmaster ">Webmaster </option> </select> <br /><br /> Mail Message: <br /> <textarea name="notes" rows="4" cols="40"></text area> <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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 43 of 65
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 $vis itormail ?> ) <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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 44 of 65
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 45 of 65
?>
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 46 of 65
Regex
Test for string occurrence: preg_match("operators",”text”); or preg_match("oper ators",$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 Description
preg_match() 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() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote() Quote regular expression characters
Common regex operators
Operator Purpose
. (period) Match any single character
^ (caret) Match the empty string that occurs at the beginning of a line or string
$ (dollar sign) Match the empty string that occurs at the end of a line
A Match an uppercase letter A
a Match a lowercase letter a
\d Match any single digit
\D Match any single nondigit character
\w Match any single alphanumeric character; a synonym is [:alnum:]
[A-E] Match any of uppercase A, B, C, D, or E
[^A-E] Match any character except uppercase A, B, C, D, or E
X? Match none or one capital letter X
X* Match zero or more capital Xes
X+ Match one or more capital Xes
X{n} Match exactly n capital Xes
X{n,m} Match at least n and no more than m capital Xes; if you omit m, the expression tries to match at least n Xes
(abc|def)+ Match a sequence of at least one abc and def; abc and def would match
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 47 of 65
Examples Example Match Does not Match
‘/hello/’ hello
‘/^hello/’ Match hello at the start of a string. Possible matches are hello or helloworld, worldhello ‘/hello$/’ hello at the end of a string. helloworld
‘/he.o/’ any character between he and o. Possible matches are helo or heyo, hello
‘/he?llo/’ llo or hello
‘/hello+/’ hello one or more times. hello or hellohello
‘/he*llo/’ llo, hello or hehello hellooo
‘/hello|world/’ either match the word hello or world It will
‘/(A-Z)/’ Using it with the hyphen character, this pattern will match every uppercase character from A to Z. E.g. A, B, C…
‘/[abc]/’ any single character a, b or c ab, bc ‘/abc{1}/’ precisely one c character after the characters ab. E.g. matches abc, abcc
‘/abc{1,}/’ one or more c character after the characters ab. E.g. matches abc or abcc Matches
‘/abc{2,4}/’ between two and four c character after the characters ab. E.g. matches abcc, abccc or abcccc,
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 48 of 65
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 h as 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 rege xen) are written in a formal language that can be interpreted by a regular expression pro cessor"; $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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 49 of 65
Cookies A cookie is used to store data for long periods of time. We might wish to remember a user’s name or phone number. A Cookie is a small flat file which sits on user’s 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 name of the cookie. Example: "username"
$value value of the cookie. Example: "john"
$expire time (in UNIX timestamp) when the cookie will expire. Example: time()+"3600". Cookie is set to expire after one hour.
$path 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 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"
$secure true if cookie is being set over a secure "https" server, false otherwise, Default value is false.
<?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*3 65)); ?>
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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 50 of 65
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*3 65)); ?>
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 51 of 65
Miscellaneous functions Function Description
connection_aborted() Checks whether the client has disconnected
connection_status() Returns the current connection status
connection_timeout() Deprecated in PHP 4.0.5
constant() Returns the value of a constant
define() Defines a constant
defined() Checks whether a constant exists
die() Prints a message and exits the current script
eval() Evaluates a string as PHP code
exit() Prints a message and exits the current script
get_browser() Returns the capabilities of the user's browser
highlight_file() Outputs a file with the PHP syntax highlighted
highlight_string() Outputs a string with the PHP syntax highlighted
ignore_user_abort() Sets whether a remote client can abort the running of a script
pack() Packs data into a binary string
php_check_syntax() Deprecated in PHP 5.0.5
php_strip_whitespace() Returns the source code of a file with PHP comments and whitespace removed
show_source() Alias of highlight_file()
sleep() Delays code execution for a number of seconds
time_nanosleep() Delays code execution for a number of seconds and nanoseconds
time_sleep_until() Delays code execution until a specified time
uniqid() Generates a unique ID
unpack() Unpacks data from a binary string
usleep() Delays code execution for a number of microseconds
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 52 of 65
MySql
� mysql_affected_rows — Get number of affected rows in previous MySQL op eration
� 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 previ ous 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 nu meric 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 fiel d 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 i s no connection
� mysql_query — Send a MySQL query
� mysql_real_escape_string — Escapes special characters in a string for use i n 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 buffe ring the result rows.
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 53 of 65
<?php /* +------------------------------------------------ -------------------+ | | | File: php_mysql_test.php Version: 2012-02-04 | | | | Purpose: shows syntax for most common mysq l 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) ; // detect all errors ini_set ( 'display_errors' , 'on' ) ; // 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 54 of 65
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'; $stri p2 = '#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 s ize='+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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 55 of 65
<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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 56 of 65
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 Type : Length
Key Index Default Extra
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
id,int(11),NO,PRI,,auto_increment name,varchar(25),YES,,, age,int(3),YES,,, updated,timestamp,NO,,CURRENT_TIMESTAMP,on update C URRENT_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 na me', `age` int(3) DEFAULT NULL COMMENT 'yrs', `updated` timestamp NOT NULL DEFAULT CURRENT_TIME STAMP 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=la tin1 ) 1 Mysql connection closed, end of program.
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 57 of 65
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 <script>)
If you use the two functions together your database will be protected and you’ll 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 Description TINYINT Small Integer Number SMALLINT Small Integer Number MEDIUMINT Integer Number INT Integer Number VARCHAR Text (maximum 256 characters) TEXT 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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 58 of 65
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"><b r> Last Name: <input type="text" name="last"><br > Phone: <input type="text" name="phone"><b r> Mobile: <input type="text" name="mobile"><b r> Fax: <input type="text" name="fax"><br> E-mail: <input type="text" name="email"><b r> 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 form’s 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 s elect 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 s elect database"); $query="SELECT * FROM contacts"; $result=mysql_query($query);
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 59 of 65
$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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 60 of 65
$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 NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 61 of 65
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 62 of 65
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 63 of 65
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 64 of 65
Notes: _______________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
PHP reference – by Jan Zumwalt NeatInfo.com – February 10, 2012
Copyright © 1995-2012
Pg 65 of 65
Notes: _______________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
Recommended