Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 PHP Introduction Chapter 1. Syntax and language constructs.

Similar presentations


Presentation on theme: "1 PHP Introduction Chapter 1. Syntax and language constructs."— Presentation transcript:

1 1 PHP Introduction Chapter 1. Syntax and language constructs

2 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

3 What is it?  A server-side scripting language designed specifically for the Web.  PHP code:  is embedded within HTML pages (similarly to JavaScript 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 JavaScript 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 JavaScript)! 3

4 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

5 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

6  http://cscdb.nku.edu/csc301/frank/PHP_ Crash_Course_Examples/orderform_1.ht ml http://cscdb.nku.edu/csc301/frank/PHP_ Crash_Course_Examples/orderform_1.ht ml  http://www.nku.edu/~frank/csc301/Exam ples/PHP_Crash_Course/processorder_1 _php.pdf http://www.nku.edu/~frank/csc301/Exam ples/PHP_Crash_Course/processorder_1 _php.pdf

7 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

8 " ?> Bob's Auto Parts - Order Results Bob's Auto Parts Order Results <?php echo ' Order processed. '; ?> 8 A mix of plain XHTML and PHP code.

9  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 element Short PHP script delimiters ASP-style script delimiters 9

10 XML style → preferred!   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   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

11 SCRIPT style  statements;  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 elements cannot be validated:  element’s language attribute is deprecated in XHTML;  Strict and transitional DTDs require using element’s type attribute, but PHP scripting engine ignores s that have type attribute. 11

12 ASP style   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:  " ?> 12

13 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

14 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

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

16 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  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 " Order processed at ", date("H:i, jS F Y"), ". "; 16 http://cscdb.nku.edu/csc301/frank/PHP_Crash_Cour se_Examples/PHPTest.php

17 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

18 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

19 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

20 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

21 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

22  http://cscdb.nku.edu/csc301/frank/PHP_ Crash_Course_Examples/orderform_2.ht ml http://cscdb.nku.edu/csc301/frank/PHP_ Crash_Course_Examples/orderform_2.ht ml  http://www.nku.edu/~frank/csc301/Exam ples/PHP_Crash_Course/processorder_2 _php.pdf http://www.nku.edu/~frank/csc301/Exam ples/PHP_Crash_Course/processorder_2 _php.pdf

23 = 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 $3DigitNumber 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

24 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

25 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.0e11)  String  Boolean – two logical values, true and false  Array – used to store multiple data items  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 reference types

26 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


Download ppt "1 PHP Introduction Chapter 1. Syntax and language constructs."

Similar presentations


Ads by Google