1 / 124

Web Programming in PHP

Web Programming in PHP. Dr. Hsiang-Fu Yu National Taipei University of Education Original by James Bowen. Reference Sites. http://www.php.net http://www.php.net/manual http://www.zend.com http://www.zend.com/manual. PHP History. PHP originally stood for “ Personal Home Page ”

khan
Télécharger la présentation

Web Programming in 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. Web Programming in PHP Dr. Hsiang-Fu Yu National Taipei University of Education Original by James Bowen

  2. Reference Sites • http://www.php.net • http://www.php.net/manual • http://www.zend.com • http://www.zend.com/manual

  3. PHP History • PHP originally stood for “Personal Home Page” • It started out, in 1994, as a simple preprocessor of HTML files • built by Rasmus Lerdorf (born in Greenland, grew up in Denmark and Canada, graduated from University of Waterloo in 1993, now prominent member of Open Source movement) • original purpose was to log people who viewed his on-line resume • Name now supposed to stand for “Hypertext Pre-Processor”

  4. PHP History (cont.) • Initially, PHP comprised a simple parser plus a library of C functions • Scan a HTML file looking for instances of a new non-standard tag • Then replace the contents of these tag instances with the result of executing some functions in the C library • Thus, much PHP syntax looks like C • Other parts of it, however, have a Perl flavour

  5. Enable PHP in HTTP (Web) Servers • PHP is available in Windows and all types of Unix environments • It is supported by Apache, AOLServer, Roxen and IIS • Here, we assume that the httpd recognizes a file who name has the suffix .php as a PHP file

  6. A first PHP file <html> <head> <title>PHP Test</title> </head> <body> <?phpecho “<p>Hello World</p>";?> </body> </html>

  7. How PHP files Are Processed • The httpd demon simply copies regular HTML content in the .php file to the message body that will be sent to a client which requests the .php file • The new non-standard tag is of the form <?php …?> • The text inside the tag is PHP code <?php echo “<p>Hello World</p>"; ?> • The httpd demon executes this PHP code and copies the output text, generated by this PHP code, to the message body that will be sent to the client • Thus, the client would see only <p>Hello World</p>

  8. Suppose That We Request This File C:\> telnet 120.127.16.64 80 Trying 120.127.16.64... Connected to 120.127.16.64. Escape character is '^]'. GET /index.php <html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p> </body> </html> Connection closed by foreign host.

  9. PHP Files Are Not Special • PHP files do not have to be executable • They can be regarded as simply HTML files with some new tags

  10. PHP Tags • In the example just seen, the PHP tag was <?php … ?> • This is the best PHP tag to use – it is the one which works best if we are also using XML, because it avoids conflicts with XML Processing Instructions • The following tags are also used • <? … ?> • <% … %> • <script language=“php”> … </script>

  11. Variables in PHP • Variables in PHP are denoted by a dollar sign followed by the name of the variable • $a, $b • A variable name is case-sensitive, like C • A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores, like C again

  12. Example of Variables <html> <head> <title>Greetings</title> </head> <body> <h1>Greetings</h1> <p> <?php $person = "Tom"; $Person = "Dick"; echo "Hello $person and $Person"; ?> </p> </body> </html>

  13. Example of Variables (cont.)

  14. Automatic Variables in PHP • One of the main benefits of PHP is that it provides lots of variables automatically • Consider, for example, the .php file on the next slide, $_SERVER[‘HTTP_USER_AGENT’] • It produces the output on the following two slides when viewed by MSIE 6.0 and Netscape 2.0

  15. Example of Automatic PHP Variable <html> <head> <title>Your browser</title> </head> <body> <h1>Your Browser</h1> <p> You are using <?phpecho $_SERVER[‘HTTP_USER_AGENT’];?> to view this page. </p> </body> </html>

  16. Example of Automatic PHP Variable (cont.)

  17. Example of Automatic PHP Variable (cont.)

  18. Data Types in PHP • PHP supports eight primitive data types • There are four scalar types • boolean • integer • floating-point number • string • There are two structured types • array • object • There are two special data types • resource • NULL

  19. Data Types in PHP (cont.) • The programmer does not need to specify the type of a variable • a variable’s type is determined from the context of its usage

  20. Booleans • The boolean data type admits two values • true (case-insensitive) • false (case-insensitive) • Example $itIsRainingToday = true; $thePrinterIsBusy = True; $theQueueIsEmpty = FALSE;

  21. Integers • Integers can be specified in decimal, hexadecimal or octal notation, optionally preceded by a sign • In octal notation, the number must have a leading0 • In hexadecimal notation, the number must have a leading 0x. • Examples $a = 1234;# decimal number $a = 0123;# octal number (i.e., 83 decimal) $a = -123;# a negative number $a = 0x1B;# hexadecimal number (i.e., 27 decimal)

  22. Integers (cont.) • The maximum size of an integer is platform-dependent, but usually it’s 32 bits signed– about 2,000,000,000 • PHP does not supportunsigned integers.

  23. Floating Point Numbers • Specified using any of these forms $a = 1.234; $a = 1.2e3; $a = 7E-10; • The maximum size of a float is platform-dependent, although most support a maximum of about 1.8e308 with a precision of roughly 14 decimal digits

  24. Strings • Specified in three different ways • single quoted • double quoted • heredoc syntax

  25. Single-quoted Strings • In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslash echo 'this is a simple string'; echo 'You can embed newlines in strings, just like this.'; echo ‘Douglas MacArthur said "I\'ll be back” when leaving the Phillipines'; echo 'Are you sure you want to delete C:\\*.*?';

  26. Double-quoted Strings • In double-quoted strings, • variables are interpreted to their values, and • various characters can be escaped • \n linefeed • \r carriage return • \t horizontal tab • \\ backslash • \$ dollar sign • \” double quote • \[0-7]{1,3} a character in octal notation • \x[0-9A-Fa-f]{1,2} a character in hexadecimal notation

  27. Heredoc Strings • Heredoc strings are like double-quoted strings without the double quotes • A heredoc string is delimited as follows • The string is preceded by <<< followed by a label • The string followed by a 2nd occurrence of the same label • Note: the second label must be put in the first position without any space or other characters • Example $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD;

  28. Functions for Strings • addcslashes • Quote string with slashes in a C style • addslashes • Quote string with slashes • bin2hex • Convert binary data into hexadecimal representation • chop • Alias of rtrim() • chr • Return a specific character

  29. Functions for Strings (cont.) • chunk_split • Split a string into smaller chunks • convert_cyr_string • Convert from one Cyrillic character set to another • count_chars • Return information about characters used in a string • crc32 • Calculates the crc32 polynomial of a string • crypt • One-way string encryption (hashing)

  30. Functions for Strings (cont.) • echo • Output one or more strings • explode • Split a string by string • get_html_translation_table • Returns the translation table used by htmlspecialchars() and htmlentities() • get_meta_tags • Extracts all meta tag content attributes from a file and returns an array

  31. Functions for Strings (cont.) • hebrev • Convert logical Hebrew text to visual text • hebrevc • Convert logical Hebrew text to visual text with newline conversion • htmlentities • Convert all applicable characters to HTML entities • htmlspecialchars • Convert special characters to HTML entities • implode • Join array elements with a string

  32. Functions for Strings (cont.) • join • Join array elements with a string • levenshtein • Calculate Levenshtein distance between two strings • localeconv • Get numeric formatting information • ltrim • Strip whitespace from the beginning of a string

  33. Functions for Strings (cont.) • md5 • Calculate the md5 hash of a string • md5_file • Calculates the md5 hash of a given filename • metaphone • Calculate the metaphone key of a string • nl2br • Inserts HTML line breaks before all newlines in a string • ord • Return ASCII value of character

  34. Functions for Strings (cont.) • parse_str • Parses the string into variables • print • Output a string • printf • Output a formatted string • quoted_printable_decode • Convert a quoted-printable string to an 8 bit string • quotemeta • Quote meta characters

  35. Functions for Strings (cont.) • str_rot13 • Perform the rot13 transform on a string • rtrim • Strip whitespace from the end of a string • sscanf • Parses input from a string according to a format • setlocale • Set locale information • similar_text • Calculate the similarity between two strings

  36. Functions for Strings (cont.) • soundex • Calculate the soundex key of a string • sprintf • Return a formatted string • strncasecmp • Binary safe case-insensitive string comparison of the first n characters • strcasecmp • Binary safe case-insensitive string comparison • strchr • Find the first occurrence of a character

  37. Functions for Strings (cont.) • strcmp • Binary safe string comparison • strcoll • Locale based string comparison • strcspn • Find length of initial segment not matching mask • strip_tags • Strip HTML and PHP tags from a string • stripcslashes • Un-quote string quoted with addcslashes()

  38. Functions for Strings (cont.) • stripslashes • Un-quote string quoted with addslashes() • stristr • Case-insensitive strstr() • strlen • Get string length • strnatcmp • String comparisons using a "natural order" algorithm

  39. Functions for Strings (cont.) • strnatcasecmp • Case insensitive string comparisons using a "natural order" algorithm • strncmp • Binary safe string comparison of the first n characters • str_pad • Pad a string to a certain length with another string • strpos • Find position of first occurrence of a string

  40. Functions for Strings (cont.) • strrchr • Find the last occurrence of a character in a string • str_repeat • Repeat a string • strrev • Reverse a string • strrpos • Find position of last occurrence of a char in a string • strspn • Find length of initial segment matching mask

  41. Functions for Strings (cont.) • strstr • Find first occurrence of a string • strtok • Tokenize string • strtolower • Make a string lowercase • strtoupper • Make a string uppercase • str_replace • Replace all occurrences of the search string with the replacement string

  42. Functions for Strings (cont.) • strtr • Translate certain characters • substr • Return part of a string • substr_count • Count the number of substring occurrences • substr_replace • Replace text within a portion of a string • trim • Strip whitespace from the beginning and end of a string

  43. Functions for Strings (cont.) • ucfirst • Make a string's first character uppercase • ucwords • Uppercase the first character of each word in a string • vprintf • Output a formatted string • vsprintf • Return a formatted string

  44. Functions for Strings (cont.) • wordwrap • Wraps a string to a given number of characters using a string break character. • nl_langinfo • Query language and locale information

  45. Arrays • An array in PHP is a structure which maps keys to values • The keys can specified explicitly or they can be omitted • If keys are omited, integers starting with 0 are keys • The value mapped to a key can, itself, be an array, so we can have nested arrays

  46. Create An Array • A special function is used to specify arrays • array() • Format of Usage array([key =>] value, …) • A key is either a string or a non-negative integer • A value can be anything

  47. Create An Array (cont.) • Format of array creation • array( [key =>] value, ... ) • A hash array $mothers = array (“tom"=>“mary", “mick"=>“ann", “bill"=>“orla"); • Implicit indices are integers, starting at 0 $places = array (“Cork”, “Dublin”, “Galway”);

  48. Create An Array (cont.) • If an explicit integer index is followed by implicit indices, they follow on from the highest previous index • Here is an array indexed by integers 1, 2, 3 $places = array (1 => “Cork”, “Dublin”, “Galway”); • Here is an array indexed by integers 1, 5, 6 $places = array (5=> “Cork”, 1 => “Dublin”, “Galway”);

  49. Create An Array (cont.) • A two-dimensional hash array $parents = array (“tom” => array (“father” => “bill”, “mother”=> “mary”), “dave” => array(“father” => “tom”, “mother” => orla”)); • A two-dimensional ordinary array $heights = array (array (10,20), array(100,200));

  50. Array Example 1 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris','Ireland'=>'Dublin'); echo 'The capital of Ireland is '; echo $capital['Ireland']; ?> </p> </body> </html>

More Related