Question? Leave a message!

Basic PHP

Basic PHP
Using PHP – Part 2  THIS WEEK  Basic PHP The PHP web site  Detailed use of forms  Handling strings  Regular expressions  Reading and writing files  Object oriented PHP  LAST WEEK  Adding PHP to a web page  Variables, constants, types  Printing strings and variables  What data is available to a PHP page  How do pages know what a user has typed into a form  Write a web form with a text box  Users type PHP code into the text box  When they hit RUN, the page executes the code and shows the results  You can do this too This is some HTML code Escaping php echo "divThis bit is coded using PHP/div"; And this is HTML again php Choosing if (condition) which bit of HTML It was true. php to display else It was false. php php Comments can be // This is a comment. shown in 3 different This is also a comment. ways / This is a multiline comment. /  Scalar types Types  boolean  integer  float (= double)  string  Compound types  array  object  Special types  resource, NULL  Two values, True and False  Case insensitive: True, TRUE, true are all the same.  The following are all considered to be false:  boolean FALSE  integer 0, float 0.0  empty string "", the string "0"  an empty array, and objects with no members  the special type NULL  Everything else is regarded as true  Integers  PHP doesn't support unsigned integers  The maximum values are platform dependent  Real numbers (various formats can be used)  1.234, 1.2e3, 7E10  Strings  'not expanded', "expanded"  can also use HEREDOC format (see manual)  Arrays  a = array(value, …); a = array(key = value, …);  To refer to a value, either of these works ▪ datakey, datakey ▪ To see the contents of an array, use printr(a);  Objects  You can define classes in PHP (see manual)  Resources  special variables holding references to external resources  these are used when extracting data from databases  NULL  variables with no value (the only value they can be assigned is also called NULL, null, Null, etc)  unset(a) makes a equal to NULL  Variables begin with a dollar sign Variables  The basic operations available are much the same as in Java, e.g. addition x = y + z;  Variables have the same type as their values  The type of a variable can change (type juggling) Assignments  x = 1;  myname = "Mike";  result = array("hi" = "there); Constants  Normal method  define("NAME", "Mike");  Version 5.3.0 onwards  const NAME = "Mike";  Can only take scalar values  if (cond) … elseif … else … Control  while (cond) … expressions  do … while (cond)  for (init; step; cond) …  break, continue  foreach (arr as val) …  foreach (arr as key = val) …  switch (val) case 'x': …; break;  default  Define functions using function hello() the function keyword echo "hello there :)"; hello();  Can define functions inside if statements if (x) function doStuff() …  Can even define functions inside other function hi() functions function there() … PHP 5 includes an function inverse(x) exceptionstyle if (x) mechanism for throw new Exception( handling errors "Can't divide by zero" ); else return 1/x; try inverse(0); catch (Exception e) …  Suppose you are asked to write a very simple formbased web page  The user types their name and then submits the form  A new page opens, saying hello  For example, if I type "mike" in the box, the new page says "Hello mike"  If the box is left empty, the new page says "Hello stranger"  How do we do this getname.php sayhello.php This page contains the form. This page is called by the form The user submits the form by when the use clicks the submit clicking a "submit" button. button. It displays the "hello" message. Later we'll see how to do both jobs using just a single page. html head title/title /head body form action="sayhello.php" Please enter your name: input type="text" name="username" / br /input type="submit" / /form /body /html html head title/title /head body php username = "stranger"; // 1 if (isset(REQUEST'username')) // 2 if (REQUEST'username') // 3 username = REQUEST'username'; // 4 // echo "Hello username"; // 5 /body /html username = "stranger"; Create a variable called username, and set it to the default value "stranger". The following instructions will check whether the user entered a string in the box before hitting the submit button. If they did, we will overwrite the value of username so it contains the string they entered. if (isset(REQUEST'username')) ... Is the value REQUEST'username' defined It's entirely possible that someone browsed to this page directly, rather than by clicking the submit button on the getname.php page, so we need to check whether they provided the information we're expecting. The isset() function tests whether or not a variable is currently defined. The keystring 'username' is the name of the corresponding form element in getname.php. if (REQUEST'username') ... ; Did the user type anything in the box before clicking "submit" If not, the value of REQUEST'username' will be the empty string, which PHP considers to be the same as FALSE. Exercise: This test will also fail if the user enters the string "0", because PHP also treats zero as FALSE. How can we avoid this problem This test does NOT fail (but probably should) if we enter a string of spaces. We'll see below how to check for this. if (...) username = REQUEST'username'; At the start of the code we set username to the default value "stranger". If we've got this far, we know that REQUEST'username' has been set, and its value isn't the empty string (or "0"). So we can now overwrite the default value with the string the user typed in. echo "Hello username"; We are now ready to display the message. Because we're using double quotes, the value of username will appear when this text is printed out.  When the user submits the form, the response currently replaces the original window. To send the response to a new window, change the form tag. form target="nameOfTargetFrame" ... You can call the target frame anything you like. Each time you submit the form, the contents of the new window are overwritten (unless the name is "blank", in which case you get a new window each time).  Sometimes you want the page to be updated when you submit a form  You already know how to do this using JavaScript.  You can also use PHP if the changes require information that's only available from the server. Suppose the page is called hello.php. We tell the form to reopen the same page, but this time with extra information provided in the querystring. php if (isset(REQUEST'key') // add extra material to the page, depending // on the value of REQUEST'key' form action="hello.php" input name="key" ... / input type="submit" / /form form action="thispage.php" select name="req" onChange="form.submit()" option value=1CLICK FOR LIST OF AVAILABLE FORMS/option php forms = array( 0 = "Where do I send a letter", 1 = "How do I advertise on the site" ); req = isset(REQUEST'req') REQUEST'req' : 1; foreach (forms as key = value) print "\noption value='key'"; if ( key == req ) print " selected"; print "value/option"; /select /form  By default, the query string is visible when a form is submitted. http://localhost/com1004/sayhello.phpusername=hiya  To keep it hidden, set the form's method attribute to "post". form method="post" ...  The default behaviour corresponds to the setting form method="get" ...  When customers submit information, you often need to send them a confirmation email. form...input name="email" type=text /.../form php if (isset(REQUEST'email')) recipient = REQUEST'email'; subject = "Confirmation"; message = "Thank you for your order"; mail(recipient, subject, message); You can add additional headers (sender, cc, bcc). See the PHP manual. All three values are regarded as FALSE echo "" "yes" : "no"; // prints "no" echo "0" "yes" : "no"; // prints "no" echo 0 "yes" : "no"; // prints "no"  The empty string, the string containing 0, and the integer value 0 are all treated by PHP as if they are the boolean value FALSE. Use == to test for equal values. Use === if the types have to match as well. str = ""; echo (str == "") "yes" : "no"; // prints "yes" echo (str === "") "yes" : "no"; // prints "yes" echo (str == "0") "yes" : "no"; // prints "no" echo (str === "0") "yes" : "no"; // prints "no" echo (str == 0) "yes" : "no"; // prints "yes" echo (str === 0) "yes" : "no"; // prints "no" number = trim(REQUEST'phone');  Users sometimes add extra spaces at the start and/or end of their input.  trim(str) removes spaces from the beginning and end of the string  ltrim(str) only trims the spaces at the start of the string  rtrim(str) only trims the spaces at the end of the string msg = "This is a very long\n" This code ... . "message, spread over\n" . "3 lines."; echo nl2br(msg); This is a very longbr / ... produces this output message, spread overbr / 3 lines. Without nl2br(), the instruction echo msg; would display the following text when displayed in HTML, because HTML ignores whitespace. This is a very long message, spread over 3 lines.  As with Java, you can format strings before printing them. outputs a formatted string to the browser printf(...) sprintf(...) outputs a formatted string to a string name = "Mike"; vat = 17.5; amount = 2.00; printf("Thanks for your order, s. Please send £.2f.", name, amount(1+vat/100)); Thanks for your order, Mike. Please send £2.35. printf("b",20); // 10100 binary value printf("c",65); // A ascii character printf("d",80); // 80 decimal printf(".2f",20); // 20.00 floating point printf("o",20); // 24 octal (base 8) printf("s","mike"); // mike string printf("u",20); // 4294967276 unsigned decimal printf("x",2078); // 81e hexadecimal (lowercase) printf("X",2078); // 81E hexadecimal (uppercase) Starting at START, follow the arrows along any path you want, until you reach STOP. What strings can you spell out along the way The collection of all possible strings that can be generated in this way is called the language recognised by the machine Finite State Machine Another way to express the same language is by using regular expressions. This machine recognises the regular expression \azAZ\w  A regular expression describes a pattern inside a string  . match any character  x match exactly one x  x+ match one or more x's  x match zero or more x's  xy match x or y  acj. match a, c, j or fullstop  az match any character from a to z  There are lots of shortcuts (see the PHP manual). For example:  \d decimal digit  \w word character (az, AZ, , 09)  \s whitespace  \t tab  \n newline \w.+\w+\.co(m\.uk) \w.+ one or more characters from az AZ 09 . the symbol \w+ one or more characters from az AZ 09 \.co the string ".co" (m\.uk) either the letter m, or the string ".uk" This regular expression describes very basic email addresses; it helps you check whether users have typed in valid addresses. regexp = '/(\w.+)()(\w+)(\.co)(m\.uk)/'; n = pregmatch(regexp, '', matches); echo "There were n matchesbr /"; foreach (matches as key = result) echo "key = resultbr /"; There were 1 matches matches0 contains the entire 0 = matched string. The other entries in 1 = m.ike matches are the substrings matched by 2 = the bits in brackets. 3 = mysite 4 = .co 5 = .uk PHP will keep a record of any substring it matches if you put that part of the regular expression in brackets. Notice that the entire regular expression should be enclosed inside slashes; this tells PHP it's a regular expression, not a string.  Before you open a file, you need to decide what you want to use it for.  read data  write new data to the end of the file  overwrite the file entirely  a mixture of these  It's not safe for two people to write to the same file at the same time; if you don't need to write, open the file in "read" mode.  You must have appropriate access rights. fp = fopen(filepath, mode); File modes r Read (starting at the beginning of the file) r+ Read/write w Write. If the file already exists, overwrite it. If it doesn't exist, try to create it. w+ Read/write. If the file already exists, overwrite it. If it doesn't exist, try to create it. x If the file exists, don't open it, return FALSE. Otherwise write. x+ If the file exists, don't open it, return FALSE. Otherwise read/write. a Append. If file doesn't exist, try to create it. a+ Append/read. If file doesn't exist, try to create it. b Binary mode (this is the default) t Text mode (only relevant when using Windows. Not recommended since it affects portability.  Writing to a file  Open the file. If it doesn't exist, you may need to create it.  Write the data to the file.  Close the file again  Reading from a file  Open the file. If it doesn't exist, handle the problem gracefully.  Read the data from the file.  Close the file again docroot = SERVER'DOCUMENTROOT'; user = REQUEST'user'; order = REQUEST'order'; if ( fp = fopen("docroot/orders.txt", 'w') ) fprintf(fp,"s\ts\n", user, order); fclose(fp); echo "pThank you for your order, user./p"; else echo "pSorry user. Please try later./p"; Next week we'll start looking at databases and MySQL. It's usually better to store data in a database than in a text file. docroot = SERVER'DOCUMENTROOT'; str = nl2br(filegetcontents("docroot/orders.txt")); str = pregreplace('/\t/','nbsp;',str); echo str; filegetcontents(filepath) returns the contents of the file as a string nl2br(str) replaces line breaks with br / tags pregreplace(pattern, replacement, string) looks for text in string that matches pattern, and replaces it with replacement  As you know, there are good reasons for using object oriented programming techniques.  PHP allows you to define and use classes.  Beware The class system was completely rewritten for PHP 5 to make it more efficient. You need to check whether your server is running PHP4 or PHP5. class Mine var n; function Mine(n) thisn = n; function toString() return "thisn"; m = new Mine(5); echo mtoString(); • The constructor has the same name as the class. • To access methods and values, use the symbol. class Mine private n; function construct(n) thisn = n; function toString() return "thisn"; m = new Mine(5); echo m; • The constructor is called construct • The magic function toString converts an object into a string, so we can type echo m to see its value. • To access methods and values, use the symbol. class BaseClass function construct() print "In BaseClass constructor\n"; class SubClass extends BaseClass function construct() parent::construct(); print "In SubClass constructor\n"; PHP doesn't support multiple inheritance.  The manual includes details of objectoriented PHP for both PHP4 and PHP5.  You should already be familiar with the basic principles of objectoriented programming, from your study of Java.  Some of the conventions are different in PHP (e.g., how to declare constructors and destructors), so don't just assume the two languages are the same.  Read the information in the manual  LAST WEEK • NEXT WEEK  Adding PHP to a web page ▫ Databases  Variables, constants, types ▫ MySQL  Printing strings and variables ▫ Using PHP with MySQL  What data is available to a PHP page  How do pages know what a user has typed into a form  THIS WEEK  Detailed use of forms  Handling strings  Regular expressions  Reading and writing files  Object oriented PHP
Document Information
User Name:
User Type:
United States
Uploaded Date: