1 / 68

PHP

PHP. What we'll cover. A short history of php Parsing Variables Arrays Operators Functions Control Structures External Data Files. Background. PHP stands for "PHP: Hypertext Preprocessor“, which is a recursive backronym.

jeromes
Download Presentation

PHP

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

  2. What we'll cover • A short history of php • Parsing • Variables • Arrays • Operators • Functions • Control Structures • External Data Files

  3. Background • PHP stands for "PHP: Hypertext Preprocessor“, which is a recursive backronym. • PHP is a server-side interpreted scripting language designed for web development but also used as a general-purpose programming language. • Syntax based on Perl, Java, and C • Very good for creating dynamic content • Powerful, but somewhat risky! • Open-Source, currently maintained by the PHP group

  4. scripting language (Interpreted) • scripting language (Interpreted) • Uses “.php” extension

  5. Server side • Server-side Used for creating dynamic webpages. • Opposed to something like Javascript, which can be used at both client-side and sever side (with ASP mechanism)

  6. History • Originally started as a Perl hack in 1994 by Rasmus Lerdorf (to handle his resume), developed to PHP/FI 2.0 • By 1997 up to PHP 3.0 with a new parser engine by Zeev Suraski and Andi Gutmans • Intended to replace a set of perl scripts he used • In 1997 two Israeli programmers rewrote the parser, released in 1998 • Based on Zend Engine, an open-source scripting engine • Renamed it to PHP: PHP Hypertext Processor, a recursive acronym • PHP 5 released in 2004, greatly improved support for OOP • Version 5.?.? is current version, rewritten by Zend (www.zend.com) to include a number of features, such as an object model • CGI scripts written in C to run his personal homepage: PHP

  7. About Zend • A Commercial Enterprise • Zend provides Zend engine for PHP for free • They provide other products and services for a fee • Server side caching and other optimizations • Encoding in Zend's intermediate format to protect source code • IDE-a developer's package with tools to make life easier • Support and training services • Zend's web site is a great resource

  8. Open source • php is one of the premier examples of what an open source project can be

  9. popular • The canonical PHP interpreter, powered by the Zend Engine, is free software released under the PHP License. PHP has been widely ported and can be deployed on most web servers on almost every operating system and platform, free of charge. • PHP was installed on several million web servers, nowadays.

  10. Standard? • Despite its popularity, no written specification or standard existed for the PHP language until 2014, leaving the canonical PHP interpreter as a de facto standard. • The reference implementation of PHP (powered by the Zend Engine) is now produced by The PHP Group. • Since 2014, there is ongoing work on creating a formal PHP specification.

  11. PHP 5 Architecture • Zend engine as parser (Andi Gutmans and Zeev Suraski) • SAPI is a web server abstraction layer • PHP components now self contained (ODBC, Java, LDAP, etc.) • This structure is a good general design for software (compare to OSI model, and middleware applications) image from http://www.zend.com/zend/art/intro.php

  12. PHP code can be simply mixed with HTML code, or it can be used in combination with various templating engines and web frameworks. • PHP code is usually processed by a PHP interpreter, which is usually implemented as a web server's native module or a Common Gateway Interface (CGI) executable. • After the PHP code is interpreted and executed, the web server sends resulting output to its client, usually in form of a part of the generated web page; for example, PHP code can generate a web page's HTML code, an image, or some other data.

  13. Operators

  14. Basic Syntax • PHP Scripts are always contained within the PHP tags • ‘<?php’ and ‘?>’ • Some servers support simply: ‘<? and ‘?>’ • Interpreter will ignore anything outside the tags • Lines end with semicolon ’;’ • Interpreter ignores white space • Comment Syntax • //Single line comment • /* Multi Line • Comment */ • PHP code blocks can be placed anywhere within HTML

  15. <html> <head> <title>My Page</title> <?php             $var ="Hello World!"; ?> </head> <body> <?php echo $var;//renders the variable as text ?> </body> </html> Basic Syntax Example

  16. <html> <head> <title>My Page</title> </head> <body> Hello World! </body> </html> Basic Syntax Example Will be interpreted as:

  17. Variables • Variables are designated by starting with a dollar sign ($), similar to Perl • $var_name • Variables are Case Sensitive • Can only contain alphanumeric characters, and underscores (_) • Must start with an underscore (_), or a letter • “Loosely Typed” Language • Do not have to declare variables • Variable datatypes automatically converted • Standard convention is to use lowercase letters only, and underscores • Opposed to the camelCasingStyle

  18. $var1 ="Hello World"; //A string $var1 =10;//An integer $var1 =3.14159265;//A float $var1 =array(1,2,3);//An integer array Loosely Typed Example The following stores various different datatypes in the same variable, but is in fact valid.

  19. Strings • Strings may use ‘Single’, or “Double” quotation marks • Single quotes may be nested within double quotes • Variables may be used within strings • A ‘.‘ may be used to concatenate Strings • Escape Sequences may be used for reserved chars: • A few string functions: • strlen: returns the length of a string • echostrlen("Hello world!");//Outputs 12 • strpos: returns position of one string in another • echostrpos("Hello world!","world");//Outputs 6 $string ="World!"; echo"Hello $string"; //Will output "Hello World!" $str1 ="Hello"; $str2 ="World!"; echo$str1 . $str2; //Will output "Hello World!"

  20. Arrays • Types of Arrays: • Numeric: An array with numeric indexes • Associative: An array with ID keys associated with values • Multidimensional: An array containing one or more arrays • Arrays follow the same naming rules as normal variables • Use Square Brackets to denote keys • $array[‘key’]

  21. $lolcats =array("I Can","Haz","Cheezburger?"); //Equivelent to $lolcats[0]="I Can"; $lolcats[1]="Haz"; $lolcats[2]="Cheezburger?"; //Access Values echo $lolcats[0]. $lolcats[1]. $lolcats[2]; //Will output: I Can Haz Cheezburger? Numeric Array

  22. $jobs =array("Farnsworth"=>"Mad Scientist","Fry"=>"Delivery Boy","Zoidberg"=>"Doctor?"); //Equivelent to $jobs['Farnsworth']="Mad Scientist"; $jobs['Fry']="Delivery Boy"; $jobs['Zoidberg']=["Doctor?"]; //Access Values echo"Zoidberg is a". $jobs['zoidberg']; //Will output: Zoidberg is a Doctor? Associative Arrays Note: Associative arrays use ‘=>’ as the assignment operator

  23. $families =array( "Griffin"=>array( "Peter", "Lois", "Megan" ), "Quagmire"=>array( "Glenn" ), "Brown"=>array( "Cleveland", "Loretta", "Junior" ) ); //Equivilent $families['Griffin'][0]='Peter'; $families['Griffin'][1]='Lois'; //Etc, You get the idea echo"Is ". $families['Griffin'][2]." a part of the Griffin family?"; //Will Output: Is Megan a part of the Griffin family? Multidimensional Arrays

  24. Control Structures • Conditionals: • if statement (Do something if condition is true) • if...else statement (If condition isnt true, do something else) • if...elseif statement (If condition isnt true, check second condition) • Switch statement (Selects one from many different code blocks) • Loops: • While (Execute a code block while a condition is true) • Do...while (Execute a code block, then if a condition is true do it again) • For (Iterate something a set amount of times) • Foreach (Iterate through each element in an array)

  25. //If/Else statement if($condition){ //condition1 is true }elseif($condition2){ //condition1 is false, and condition2 is true }else{ //condition1, and condition2 are false } //Switch statement switch($x){ case'a': echo"case a"; break; case'b': echo"case b"; break; case'c': echo"case c"; break; } Conditionals

  26. //While Loop $i=1; while($i<=5){ echo"$i, ";   $i++; } //Will result in: 1, 2, 3, 4, 5 //Do While Loop $i=1; do{   $i++; echo"$i, "; }while($i<=5); //Will result in: 2, 3, 4, 5, 6 While Loops

  27. //For Loop for($i=1; $i<=5; $i++{ echo"$i, "; } //Will result in: 1, 2, 3, 4, 5 //Foreach loop $array =array("one","two","three"); foreach($array as $element){ echo"$element, "; } //Will result in: one, two, three For Loops

  28. function hello($name){     $var ="Hello, ". $name; return $var; } echo hello("World"); Functions • Unlike variables, function names are not case sensitive • Do not have to predefine return type • Do not have to define parameter datatypes • No need to prototype functions • Can be called from anywhere within the scope

  29. Forms • Forms are used for input from the user • Forms are written in plain HTML • They send variables to a specified php script • Can be used for almost anything: • Username/password login • Search box • Post a message

  30. <html> • <body> • <formaction="welcome.php"method="post"> • First Name: <inputtype="text"name="fname"/><br> • Last Name: <inputtype="text"name="lname"/><br> • <inputtype="submit"/> • </form> • </body> • </html> form Example

  31. <? //Get variables from POST     $fname = $_POST['fname'];     $fname = $_POST['lname']; //Echo the variables echo"Welcome $fname $lname."; ?> form Example • When submit is clicked on the form it will send you to a script like this • Accesses the submitted information, and echos it

  32. Post • Two methods of sending the form data to the script • ‘Method” attribute in the opening form tag • <formaction="welcome.php"method="post"> • Post will ‘post’ the data to the server • Accessed using $_POSTarray • The array element is the same name as the form element • I.E. : $_POST['name'] • Where ‘name’ (in quotes) is the form elements name attribute

  33. Post • Two methods of sending the form data to the script • ‘Method” attribute in the opening form tag • <formaction="welcome.php"method="post"> • Post will ‘post’ the data to the server • Accessed using $_POSTarray • The array element is the same name as the form element • I.E. : $_POST['name'] • Where ‘name’ (in quotes) is the form elements name attribute

  34. Get • Alternative method • Less secure • Get puts the variables right in the URL • http://localhost/welcome.php?fname=Hunter&lname=Thompson • Can change the variables simply by changing the URL • Accessed as a variable using: $_GET['name'] • Where ‘name’ (in quotes) is the form elements name attribute

  35. Include • Function used to insert the contents of one PHP file into another • include("path/to/file.php"); • Useful in several ways • Include a header, footer, or any other part of a page that will be used multiple times • Organize your code better, keep functions or classes in their own files • Require is an identical function except for one respect • require("path/to/file.php"); • If the file cannot be found include will issue a warning and continue with the script • Require will throw an error and halt execution of the script if the file cannot be found

  36. PHP Scripts • Typically file ends in .php--this is set by the web server configuration • Separated in files with the <?php ?> tag • php commands can make up an entire file, or can be contained in html--this is a choice…. • Program lines end in ";" or you get an error • Server recognizes embedded script and executes • Result is passed to browser, source isn't visible <P> <?php $myvar = "Hello World!"; echo $myvar; ?> </P>

  37. Parsing • We've talk about how the browser can read a text file and process it, that's a basic parsing method • Parsing involves acting on relevant portions of a file and ignoring others • Browsers parse web pages as they load • Web servers with server side technologies like php parse web pages as they are being passed out to the browser • Parsing does represent work, so there is a cost

  38. Two Ways • You can embed sections of php inside html: • Or you can call html from php: <BODY> <P> <?php $myvar = "Hello World!"; echo $myvar; </BODY> <?php echo "<html><head><title>Howdy</title> … ?>

  39. What do we know already? • Much of what we learned about javascript holds true in php (but not all!), and other languages as well $name = "bil"; echo "Howdy, my name is $name"; echo "What will $name be in this line?"; echo 'What will $name be in this line?'; echo 'What's wrong with this line?'; if ($name == "bil") { // Hey, what's this? echo "got a match!"; }

  40. Variables • Typed by context (but one can force type), so it's loose • Begin with "$" (unlike javascript!) • Assigned by value • $foo = "Bob"; $bar = $foo; • Assigned by reference, this links vars • $bar = &$foo; • Some are preassigned, server and env vars • For example, there are PHP vars, eg. PHP_SELF, HTTP_GET_VARS 00

  41. phpinfo() • The phpinfo() function shows the php environment • Use this to read system and server variables, setting stored in php.ini, versions, and modules • Notice that many of these data are in arrays • This is the first script you should write… 00_phpinfo.php

  42. Variable Variables • Using the value of a variable as the name of a second variable)$a = "hello";$$a = "world"; • Thus:echo "$a ${$a}"; • Is the same as:echo "$a $hello"; • But $$a echoes as "$hello"…. 00_hello_world.php

  43. Operators • Arithmetic (+, -, *, /, %) and String (.) • Assignment (=) and combined assignment$a = 3;$a += 5; // sets $a to 8;$b = "Hello ";$b .= "There!"; // sets $b to "Hello There!"; • Bitwise (&, |, ^, ~, <<, >>) • $a ^ $b (Xor: Bits that are set in $a or $b but not both are set.) • ~ $a (Not: Bits that are set in $a are not set, and vice versa.) • Comparison (==, ===, !=, !==, <, >, <=, >=)

  44. Coercion • Just like javascript, php is loosely typed • Coercion occurs the same way • If you concatenate a number and string, the number becomesa string 17_coercion.php

  45. Operators: The Movie • Error Control (@) • When this precedes a command, errors generated are ignored (allows custom messages) • Execution (` is similar to the shell_exec() function) • You can pass a string to the shell for execution:$output = `ls -al`;$output = shell_exec("ls -al"); • This is one reason to be careful about user set variables! • Incrementing/Decrementing++$a (Increments by one, then returns $a.)$a++ (Returns $a, then increments $a by one.)--$a (Decrements $a by one, then returns $a.)$a-- (Returns $a, then decrements $a by one.)

  46. Son of the Valley of Operators • Logical$a and $b And True if both $a and $b are true.$a or $b Or True if either $a or $b is true.$a xor $b Xor True if either $a or $b is true, but not both.! $a Not True if $a is not true.$a && $b And True if both $a and $b are true.$a || $b Or True if either $a or $b is true. • The two ands and ors have different precedence rules, "and" and "or" are lower precedence than "&&" and "||" • Use parentheses to resolve precedence problems or just to be clearer

  47. Control Structures • Wide Variety available • if, else, elseif • while, do-while • for, foreach • break, continue, switch • require, include, require_once, include_once

  48. Control Structures • Mostly parallel to what we've covered already in javascript • if, elseif, else, while, for, foreach, break and continue

  49. Switch • Switch, which we've seen, is very useful • These two do the samethings…. switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; }

  50. Nesting Files • require(), include(), include_once(), require_once() are used to bring in an external file • This lets you use the same chunk of code in a number of pages, or read other kinds of files into your program • Be VERY careful of using these anywhere close to user input--if a hacker can specify the file to be included, that file will execute within your script, with whatever rights your script has (readfile is a good alternative if you just want the file, but don't need to execute it) • Yes, Virginia, remote files can be specified

More Related