PHP Introduction Chapter 1 Syntax and language constructs

  • Slides: 26
Download presentation
PHP Introduction Chapter 1. Syntax and language constructs 1

PHP Introduction Chapter 1. Syntax and language constructs 1

PHP • Stands for: Personal Home Page (originally), PHP: Hypertext Preprocessor (now; follows GNU’s

PHP • Stands for: Personal Home Page (originally), PHP: Hypertext Preprocessor (now; follows GNU’s recursive naming convention). • Developed: Created by Rasmus Lerdorf in ’ 94 Became later an Open Source project, developed and maintained by the PHP Group Ø Open Source project = you have access to the source code, and you can use, alter and redistribute it without charge • Current release: 5. 4. 0 • Home page for PHP: http: //www. php. net 2

PHP • What is it? A server-side scripting language designed specifically for the Web.

PHP • What is it? A server-side scripting language designed specifically for the Web. PHP code: Ø is embedded within HTML pages (similarly to Java. Script scripts); extension is. php Ø is interpreted at the Web server each time the page is visited you can only execute PHP scripts through a Web server with PHP installed! Ø generates (= creates on the fly) (X)HTML or Java. Script or other output that the visitor will see on the client tier Ø IMPORTANT: a client will never see the PHP code, only the (X)HTML that the Web server returns from the script the browser doesn’t (need to) understand PHP (different from client-side Java. Script)! 3

PHP Crash Course – Key Topics • Embedding PHP in XHTML • Adding dynamic

PHP Crash Course – Key Topics • Embedding PHP in XHTML • Adding dynamic content • Accessing form variables • Identifiers • Variables: types, declarations, assignments, scope • Operators and precedence • Using variable functions • Expressions • Selections and loops 4

Embedding PHP in HTML • Running example: a script to process an HTML form

Embedding PHP in HTML • Running example: a script to process an HTML form (a common application of any server-side scripting language) An order form for Bob’s Auto Parts, a fictional spare parts company. Form’s action is set to processorder_1. php, the name of the PHP script that will process the customer’s order. Note: choose meaningful names for the form fields, as they will be reused in the. php script that processes the form. 5

Bob’s Auto Parts version #1 http: //cscdb. nku. edu/csc 301/frank/PHP_Cr ash_Course_Examples/orderform_1. html http: //www.

Bob’s Auto Parts version #1 http: //cscdb. nku. edu/csc 301/frank/PHP_Cr ash_Course_Examples/orderform_1. html http: //www. nku. edu/~frank/csc 301/Example s/PHP_Crash_Course/processorder_1_ph p. pdf

Embedding PHP in HTML • A script to process a form. II. PHP script

Embedding PHP in HTML • A script to process a form. II. PHP script for processing the form, the processorder_1. php file. The PHP code is typed directly into a Web page as a separate section. A Web page document containing PHP code must have. php extension. When a. php document is requested → Web server sends it to the PHP scripting engine for processing; → Scripting engine processes only the PHP code located within PHP code blocks, and ignores the non-PHP code; → If your page contains only XHTML, use. html extension to avoid the extra step of having the file processed by the scripting engine. 7

processorder_1. php <? php echo "<? xml version="1. 0" encoding="UTF-8"? >" ? > <!DOCTYPE

processorder_1. php <? php echo "<? xml version="1. 0" encoding="UTF-8"? >" ? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <html xmlns="http: //www. w 3. org/1999/xhtml" > <head> <title> Bob's Auto Parts - Order Results </title> </head> <body> <h 1>Bob's Auto Parts</h 1> <h 2>Order Results </h 2> <? php echo '<p> Order processed. </p>'; ? > </body> </html> A mix of plain XHTML and PHP code. 8

Creating PHP Code Blocks PHP code declaration blocks are separate sections within a Web

Creating PHP Code Blocks PHP code declaration blocks are separate sections within a Web page that are interpreted by the PHP scripting engine. Any number of code declaration blocks can be included within a document. Code declaration blocks are delimited by PHP tags, which mark where the PHP code starts and finishes. • Any text outside these tags is treated as normal HTML. There are four types of delimiters (PHP tags) that can be used with code declaration blocks to escape from HTML : • • Standard PHP script delimiters aka XML style script delimiters The <script> element Short PHP script delimiters ASP-style script delimiters 9

PHP Code Blocks Delimiters • XML style → preferred! <? php statements; ? >

PHP Code Blocks Delimiters • XML style → preferred! <? php statements; ? > Preferred because: Ø Compliant with XML Ø Guaranteed to be available on any Web server that supports PHP, while short style and ASP style delimiters can be turned off (=disabled). • Short style <? statements; ? > Not recommended because: Ø Will not work in many environments as not enabled by default anymore; short_open_tag directive in php. ini configuration file to control feature (Note: short delimiters work on cscdb. nku. edu) Ø Not XML compliant Ø Especially if your code will be redistributed and used on other servers 10

PHP Code Blocks Delimiters • SCRIPT style <script language=“php”> statements; </script> No type attribute!

PHP Code Blocks Delimiters • SCRIPT style <script language=“php”> statements; </script> No type attribute! (such as type=“text/javascript”) Use when your HTML editor doesn’t recognize other delimiters. Always available on any Web server that supports PHP. Problems - documents that include PHP <script> elements cannot be validated: Ø <script> element’s language attribute is deprecated in XHTML; Ø Strict and transitional DTDs require using <script> element’s type attribute, but PHP scripting engine ignores <script>s that have type attribute. 11

PHP Code Blocks Delimiters • ASP style <% statements; %> Not recommended because: Ø

PHP Code Blocks Delimiters • ASP style <% statements; %> Not recommended because: Ø Not XML compliant Ø Can be disabled: asp_tags directive in php. ini configuration file to control feature Ø (Note: ASP style delimiters do NOT work on cscdb. nku. edu) • Note: xml declaration that starts an XHTML document should be printed from PHP code: <? php echo "<? xml version="1. 0" encoding="UTF-8"? >" ? > 12

PHP Statements, Whitespace, Comments • Statements: Statements = the individual lines of code that

PHP Statements, Whitespace, Comments • Statements: Statements = the individual lines of code that make up a PHP script Example: Ø echo prints (or echoes) the string passed to it in the Web page returned to the browser; the string argument can be any XHTML code PHP requires statements to be terminated with a semicolon Ø Several statements are allowed on the same line The closing tag of a PHP code block automatically implies a semicolon you don’t need to have a semicolon terminating the last line of a PHP block. • Whitespace (newlines, spaces, tabs) is ignored by the PHP engine Should be used to enhance readability of your PHP code 13

PHP Statements, Whitespace, Comments • Comments are ignored by the PHP engine too; three

PHP Statements, Whitespace, Comments • Comments are ignored by the PHP engine too; three styles: Multiline Java-style comment: /* …. Your comment here …. */ Single-line Java-style comment: // …. Your comment here …. Single-line shell script style comment: # …. Your comment here …. (Single-line comments end at end of the line or the closing PHP tag, whichever comes first) // here is a comment ? > here is not 14

Adding Dynamic Content • Adding the current date (on the server machine) to a

Adding Dynamic Content • Adding the current date (on the server machine) to a page: <? php echo "<p> Order processed at "; echo date("H: i, j. S F Y"); echo ". </p>"; ? > • PHP has an extensive library of built-in functions: The built-in date() function expects a format string argument, representing the style of output Year you want Hour in 24 -hour format with leading zero if nec. Minutes with Day of the H: i, j. S F Y leading zero month if nec. without leading zero Ordinal suffix (nd, rd, th) Full name of month 15

Adding Dynamic Content – cont • PHP has an extensive library of built-in functions:

Adding Dynamic Content – cont • PHP has an extensive library of built-in functions: The built-in phpinfo() function Outputs information about current state of PHP, so you can quickly find out what’s on your server machine: PHP version, the PHP environment, including PHP directives’ values such as asp_tags http: //cscdb. nku. edu/csc 301/frank/PHP_Crash_Course_Exa mples/PHPTest. php Note: echo and its equivalent print statements that create content on a Web page are language constructs of the PHP programming language, are NOT functions, although you can use parentheses with their argument lists: echo "<p> Order processed at ", date("H: i, j. S F Y"), ". </p>"; 16

Accessing Form Variables • Within PHP scripts, each form field can be accessed as

Accessing Form Variables • Within PHP scripts, each form field can be accessed as a PHP variable whose name relates to the name of the form field. Note: all PHP variable names start with a dollar sign $ • Three ways to access form data through variables depending on PHP version used and settings in the PHP configuration file php. ini Short style: $field_name Medium style: $_POST[‘field_name’] Long style: $HTTP_POST_VARS[‘field_name’] Short, medium and long style are not official names! 17

Accessing Form Variables • Short style: $field_name (such as $tireqty for our form) Convenient

Accessing Form Variables • Short style: $field_name (such as $tireqty for our form) Convenient Ø Names of variables in the script are the same as the names of the form fields in the HTML form Ø You don’t have to declare / create these variables in your script Ø They are passed into your script, as arguments are passed to a function But requires register_globals configuration setting to be turned on Ø This setting is turned off by default in PHP versions 4. 2. 0 and greater, deprecated as of PHP 5. 3. 0 and removed as of PHP 6. 0. 0. Ø Reason is the register_globals directive turned on represents a security risk. As form variables are automatically turned into global variables, it is difficult to make distinction between variables you have created and untrustable variables coming directly from the user (see next) 18

Accessing Form Variables • Short style: $field_name Ø Common example: <? php // $authorized

Accessing Form Variables • Short style: $field_name Ø Common example: <? php // $authorized should be true only if user is authenticated if (authenticated_user()) $authorized = true; // as $authorized wasn’t initialized to false, it might be injected // through register_globals, like from GET auth. php? authorized=1 // So, anyone can be seen as authenticated! if ($authorized) include "/highly/sensitive/data. php"; ? > 19

Accessing Form Variables • Medium style: $_POST[‘field_name’] (such as $_POST[‘tireqty’]) Recommended approach Involves retrieving

Accessing Form Variables • Medium style: $_POST[‘field_name’] (such as $_POST[‘tireqty’]) Recommended approach Involves retrieving form variables from one of the following arrays, called the superglobal arrays (will discuss with variable scope): Ø $_POST → if method used to submit the form was post Ø $_GET → if method used to submit the form was get Ø $_REQUEST → in either case, form data is also available through this array Short versions of variable names can be created for ease-of-use. A block that only creates short variable names without producing any output can be placed at the start of the processing PHP file. $tireqty = $_POST[‘tireqty’]; // creates a short variable name and // assigns the contents of $_POST[‘tireqty’] to the new variable 20

Accessing Form Variables • Long style: $HTTP_POST_VARS[‘field_name’] (such as $HTTP_POST_VARS[‘tireqty’]) Requires register_long_arrays configuration setting

Accessing Form Variables • Long style: $HTTP_POST_VARS[‘field_name’] (such as $HTTP_POST_VARS[‘tireqty’]) Requires register_long_arrays configuration setting to be turned on register_long_arrays is deprecated, usually turned off for performance reasons 21

Bob’s Auto Parts version #2 http: //cscdb. nku. edu/csc 301/frank/PHP_Cr ash_Course_Examples/orderform_2. html http: //www.

Bob’s Auto Parts version #2 http: //cscdb. nku. edu/csc 301/frank/PHP_Cr ash_Course_Examples/orderform_2. html http: //www. nku. edu/~frank/csc 301/Example s/PHP_Crash_Course/processorder_2_ph p. pdf

Identifiers • = Names for variables, functions, classes • Rules: Identifiers can be of

Identifiers • = Names for variables, functions, classes • Rules: Identifiers can be of any length and consist of letters, numbers and underscores Identifiers cannot begin with a digit; ex $3 Digit. Number is not a valid variable name Identifiers are case sensitive; Function names are an exception to this rule (their names can be used in any case) Other PHP language constructs are also case-insensitive; ex: echo Echo A variable can have the same name as a function – avoid! Two functions cannot share a name A variable name: $identifier 23

Using Variables • In addition to the predefined variables that you are (possibly) passed

Using Variables • In addition to the predefined variables that you are (possibly) passed from an HTML form, you can declare & use your own variables PHP does not require variables to be declared explicitly before they are used A variable is created when you first assign a value to it $totalqty = 0; // for number of items ordered $totalamount = $totalqty; // for total amount payable Actually, you create and initialize a variable in the same statement! (No var keyword, no declared type!) 24

PHP’s Data Types • Basic data types: Integer – used for whole numbers (-250,

PHP’s Data Types • Basic data types: Integer – used for whole numbers (-250, 2, 100, 10, 000) Float (also called double) – used for real numbers (-6. 16, 2. 7541, 2. 0 e 11) String Boolean – two logical values, true and false Array – used to store multiple data items reference types Object – used to store instances of classes • Special types: NULL – variables that: have not been assigned values, have been unset, have been assigned the specific value NULL are of type NULL Resource – certain built-in functions return values of type resource, representing usually external resources, such as database connections, or references to XML files – usually not directly manipulated, but passed to other functions as arguments 25

PHP’s Data Types • String “literals” can be specified in 4 different ways Enclosed

PHP’s Data Types • String “literals” can be specified in 4 different ways Enclosed in double quotations signs – can contain simple variables the variable will be replaced with its contents within the string, process known as interpolation $v = 3; echo “$v is a number”; displays 3 is a number Enclosed in single quotations signs – can also contain variable names; however strings within ‘’ are treated as true literals and are not evaluated variable names and any other text are unaltered 26