PHP syntax 2 ©John Samuel 2008 Objectives At the end of this class the student will be able to; Write and execute simple PHP programs using the following language features: C – like control structures Foreach Regular expressions (POSIX and Perlbased). ©John Samuel 2008 Objectives At the end of this class the student will be able to; Use PHP to interact with a MySql database. Protect database passwords through the use of functions. ©John Samuel 2008 Operators C-like operator behaviour. String concatentation operator is ‘.’ Charts and details at php.net ©John Samuel 2008 Control Standard if/elseif/else structure. foreach is useful for looping through arrays. Standard while/do while structures. Standard for structure. Standard switch statements. Note alternate syntaxes for if, while, switch, foreach and for. See http://ca.php.net/manual/en/language.control-structures.php for more details. ©John Samuel 2008 Regular expressions There are two main sets of functions to deal with regexps in PHP, one dealing with POSIX syntax, and the other with Perl syntax http://www.php.net/manual/en/ref.pcre.php http://www.php.net/manual/en/ref.regex.php ©John Samuel 2008 Regular expressions ereg()/eregi() ereg_replace()/eregi_replace() split()/spliti() http://www.php.net/manual/en/ref.regex.php ©John Samuel 2008 Regular expressions Allows use of Perl style regexps, including / / and switches such as i, m, and s. preg_match()/preg_match_all() preg_replace preg_split() http://www.php.net/manual/en/ref.pcre.php ©John Samuel 2008 Metacharacters-reference Char. Example Effect [] [afhp] Matches a or f or h or p (only one) [] [A-Za-z] Matches any one letter in the alphabet, upper or lower ^ [^af] Matches any one character, except the letter a or f . . Matches any one character, except the newline () (AGG) Treats AGG as a group, and must match them together ? T? T must be found 0 or 1 times only + T+ T must be found 1 or more times in a row * T* T can be found 0 or any number of times in a row {} T{3,6} T must be found at least 3 but no more than 6 times in a row {} T{,4} T can be found from 0 to 4 times in a row {} T{3,} T must be found at least 3 times in a row {} T{2} T must be found exactly 2 times in a row | the|thee Matches the or thee ©John Samuel 2008 Metacharacters-examples /GAA{2}/ /(GAA){2}/ matches GAAA (G then A then A twice more) matches GAAGAA (GAA twice in a row) / [^The]/ /^The/ matches any one character except T or h or e matches word The, but only at the start of a line /^INT522$/ matches INT522 only if it is alone on that line i.e. it says that I must be the first character on the line and 2 must be the last character on the line. ©John Samuel 2008 Metacharacters-reference (Perl) Char. Meaning Same as \w Any digit, underscore, upper or lowercase letter [0-9a-zA-Z_] \W Any character except a digit, underscore, upper or lowercase letter [^0-9a-zA-Z_] \d Any digit [0-9] \D Any character except a digit [^0-9] \s A newline, space, tab, or return character [\n \t\r] \S A character except a newline, space, tab, or return [^\n \t\r] \b A boundary before or after a word ©John Samuel 2008 How do I… create my own php functions Passing parameters Can return any type, including array Scope Variables in main not normally visible in function – pass parameters Parameters only have scope in function, and changes to them don’t affect originals ©John Samuel 2008 How do I… create my own php functions Creating and using php functions in separate file: 1. Write the function, putting it in <?php ?> 2. Store it in a file with .inc extension. 3. Use the keyword include with the URL of the .inc file. 4. Use the function name as if it were predefined. 5. You must not forget to put your code in php tags. See util.inc for an example. ©John Samuel 2008 die All functions in PHP return a false value if they fail. Due to this, or combined with the die function can be used to provide instructions if a function fails. Same as in Perl. ©John Samuel 2008 Database access PHP integrates very well with MySql, as well as most common databases. There is a set of functions for each supported database. Unfortunately there is not a standard set the way there is with Perl’s DBI. What implications does this have? MySql support must be enabled – use phpinfo() to check if unsure. ©John Samuel 2008 MySql Comprehensive set of functions http://www.php.net/manual/en/ref.mysql.php ©John Samuel 2008 Steps Get a connection Select desired database Perform desired queries Close connection ©John Samuel 2008 Connection Use function mysql_connect ( [string server [, string username [, string password]]]) mysql_pconnect ( [string server [, string username [, string password]]]) or If no options provided, server is assumed to be localhost. Port can optionally be added to server name. Returns a link identifier (to keep track of multiple connections), or FALSE if unable to connect. Use or and die to handle a FALSE condition, and give a useful error message. @ in front of function suppresses system error message (can be used for any PHP function). ©John Samuel 2008 Connection The link identifier is only needed when you are working with multiple connections (e.g. to different databases). ©John Samuel 2008 Connection The difference between mysql_connect and mysql_pconnect: mysql_connect is lost when the program ends mysql_pconnect is persistent, and remains active as long as the Apache child process remains active. Calling mysql_pconnect more than once with the same arguments will cause it to re-use the existing connection. This can be more efficient, and can be a good programming practice in certain cases. Study the PHP documentation http://www.php.net/manual/en/features.persistent-connections.php to see if persistent connections make sense in your case. ©John Samuel 2008 Select db You must select the desired database mysql_select_db ( string database_name [, resource link_identifier]) You may want to work with multiple connections to different databases at the same time, in which case the link identifier is needed. If omitted, it will use the most recently opened connection. ©John Samuel 2008 Run queries Use resource mysql_query ( string query [, resource link_identifier [, int result_mode]]) to execute a query. If the returned value is false, the query failed. To test number of rows affected, use int mysql_affected_rows ( [resource link_identifier]) ©John Samuel 2008 Accessing returned results array mysql_fetch_array ( resource result [, int result_type]) returns an array or FALSE if there is no data left. It can be used in a loop and will get a new row each time. The array can (by default) be used either with indices or with keys (the names of the fields in the database). array mysql_fetch_row ( resource result) is similar to mysql_fetch_array , but mysql_fetch_row the data can only by index. ©John Samuel 2008 with be accessed Quotes Use the function string addslashes ( string str) to escape any characters such as ‘ that may cause problems in a query. Use of this function can also be a helpful security measure to avoid SQL injection attacks. ©John Samuel 2008 Error handling The error returned from MySql can be accessed via string mysql_error ( [resource link_identifier]) and used with die() for an error message. ©John Samuel 2008 Freeing memory Using the function bool mysql_free_result ( resource result) can be used in programs working with many queries, or large datasets, to free results, but PHP uses garbage collection (like Java), so you don’t usually have to worry about it. Otherwise, the memory is cleared when the program ends. ©John Samuel 2008 Close Except for persistent connections, connections are closed when your program ends, but you can close a connection with the following function: bool mysql_close ( [resource link_identifier]) It is considered good programming practice to do this anyway. ©John Samuel 2008 Simple functions Creating and using functions in php is simple. Write the function, putting it in <?php ?> Store it in a file with a .inc convention. Use the keyword include with the URL of the .inc file. Use the function name as if it were predefined. You must not forget to put your code in php tags. See util.inc for an example. ©John Samuel 2008 How do I… process a web form How you process form data depends on the setting of the variable register_globals in the php.ini file. The default in php >= 4.2.0 is off. Excerpt from php.ini ; You should do your best to write your scripts so that they do not require ; register_globals to be on; Using form variables as globals can easily lead ; to possible security problems, if the code is not very well thought of. register_globals = Off ©John Samuel 2008 How do I… process a web form Setting register_globals to off is recommended to enhance security. This is the case with zenit. You access form data one of two ways. ©John Samuel 2008 How do I… process a web form You can use the built-in PHP variables $_GET, $_POST, and $_REQUEST. These are all associative arrays. You can also use $HTTP_GET_VARS and $HTTP_POST_VARS. See envvars.php You must use the exact name of the form field as a hash key, including case. E.g. if the form has a field named ‘fname’ <? print "$_REQUEST[fname]\n"; ?> ©John Samuel 2008 How do I… process a web form You can use the function bool import_request_variables ( string types [, string prefix]) types can be a combination of g,p,c (case-insensitive). prefix will be added to all form field names to create variable names. you must use the exact name of the form field (preceded by the prefix if used) as a variable, including case. ©John Samuel 2008 How do I… process a web form E.g. if the form has a field named ‘fname’ import_request_variables("gp“, “myvar_”); print "your answer is $myvar_fname\n"; import_request_variables("gp“); print "your answer is $fname\n"; NOTE: myvar_ is used here for example only. Do not use this string. You must use a string of your own that has meaning in your code. ©John Samuel 2008 How do I… process a web form You can preserve values in radio buttons etc. using the same technique as you did with Perl. ©John Samuel 2008 How do I… create a self-referent program Test to see if form should be displayed or processed See selfrefform.php Instead of param() use $_REQUEST, or $_GET or $_POST e.g. if ($_REQUEST) { //process form } else { // display form } ©John Samuel 2008 How do I… create a self-referent program One problem with using $_REQUEST is that it will contain values if there are cookies involved, even if no form data was sent. ©John Samuel 2008 How do I… work with sessions and cookies Sessions are used to maintain state between HTTP requests. Cookies are used to store session information. A session id is generated by php, and stored in a cookie. A cookie will last until the browser is closed (default), or for the value in seconds of session.cookie_lifetime in php.ini, if set. ©John Samuel 2008 How do I… work with sessions and cookies See example. Note that PHP handles creation of session ids and cookies. Note that you must still invalidate the cookie to ‘logout’. ©John Samuel 2008 How do I… work with flat files Function-based See example ©John Samuel 2008 How do I… work with environment variables Equivalent to %ENV $_SERVER ©John Samuel 2008 Review Remember that there are two sets of regular expression functions in PHP. ©John Samuel 2008