1 / 26

PHP Introduction

PHP Introduction. Chapter 1. Syntax and language constructs. PHP. Stands for: Personal Home Page (originally), PHP: Hypertext Preprocessor (now; follows GNU’s recursive naming convention). Developed: Created by Rasmus Lerdorf in ’94

deenar
Download Presentation

PHP Introduction

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Introduction Chapter 1. Syntax and language constructs

  2. PHP • Stands for: • Personal Home Page (originally), • PHP: Hypertext Preprocessor (now; follows GNU’s recursive naming convention). • Developed: • Created by RasmusLerdorf 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

  3. PHP • 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)!

  4. 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

  5. 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.

  6. Bob’s Auto Parts version #1 http://cscdb.nku.edu/csc301/frank/PHP_Crash_Course_Examples/orderform_1.html http://www.nku.edu/~frank/csc301/Examples/PHP_Crash_Course/processorder_1_php.pdf

  7. Embedding PHP in HTML • A script to process a form. • 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.

  8. processorder_1.php A mix of plain XHTML and PHP code. <?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title> Bob's Auto Parts - Order Results </title> </head> <body> <h1>Bob's Auto Parts</h1> <h2>Order Results </h2> <?php echo '<p> Order processed.</p>'; ?> </body> </html>

  9. 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

  10. 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

  11. 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.

  12. 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\"?>" ?>

  13. 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

  14. 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

  15. Adding Dynamic Content Year 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 • Adding the current date (on the server machine) to a page: <?php echo "<p> Order processed at "; echo date("H:i, jS 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 you want H:i, jS F Y

  16. Adding Dynamic Content – cont http://cscdb.nku.edu/csc301/frank/PHP_Crash_Course_Examples/PHPTest.php • PHP has an extensive library of built-in functions: • The built-inphpinfo()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 printstatements 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, jS F Y"), ".</p>";

  17. 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!

  18. 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)

  19. 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"; ?>

  20. 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

  21. 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

  22. Bob’s Auto Parts version #2 http://cscdb.nku.edu/csc301/frank/PHP_Crash_Course_Examples/orderform_2.html http://www.nku.edu/~frank/csc301/Examples/PHP_Crash_Course/processorder_2_php.pdf

  23. 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 $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

  24. 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!)

  25. PHP’s Data Types reference 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.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

  26. 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

More Related