server side programming in php n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Server-side Programming in PHP PowerPoint Presentation
Download Presentation
Server-side Programming in PHP

play fullscreen
1 / 114

Server-side Programming in PHP

102 Views Download Presentation
Download Presentation

Server-side Programming in PHP

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Server-side Programming in PHP

  2. History of PHP • 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 U of Waterloo in 1993, now prominent member of Open Source movement) • original purpose was to log people who viewed his on-line resume • Since then, has been developed by a growing community of open source developers • Name now supposed to stand for “Hypertext Pre-Processor”

  3. PHP history (contd.) • Initially, PHP comprised a simple parser plus a library of C functions • The parser would scan a HTML file looking for instances of a new non-standard tag and replace the contents of these tag instances with the result of executing some functions in the C library • As a result, much PHP syntax looks like C • Other parts of it, however, have a Perl flavour – but, of course, Perl also borrows C syntax

  4. Enabling PHP in HTTP servers • PHP is available on many servers today, in Windows and all types of Unix environments • It is supported by Apache, AOLServer, Roxen and others • Servers can be configured to enable PHP in different ways • We will assume that the httpd recognizes a file who name has the suffix .php as a PHP file

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

  6. 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 <?phpecho “<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, from the above, the client would see only <p>Hello World</p>

  7. Suppose we request this file interzone.ucc.ie> telnet student.cs.ucc.ie 80 Trying 143.239.211.125... Connected to student.cs.ucc.ie. Escape character is '^]'. GET /cs4400/jabowen/php/file1.php HTTP/1.1 Host: student.cs.ucc.ie

  8. Here is the response HTTP/1.1 200 OK Date: Wed, 06 Feb 2002 12:34:15 GMT Server: Apache/1.3.20 (Unix) PHP/4.0.6 X-Powered-By: PHP/4.0.6 Transfer-Encoding: chunked Content-Type: text/html 58 <html> <head> <title>PHP test</title> </head> <body> <p>Hello world!</p></body> </html> 0 Connection closed by foreign host. interzone.ucc.ie>

  9. cs 3314 got here on 27 oct 2005

  10. Note following in response: • Chunked transfer-encoding is used • because the httpd demon does not know, before executing the PHP content, how long the message body will be • PHP code has been replaced, in the message body, by its output

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

  12. 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 • However, you may occassionally see the following tags being used in other people’s PHP code: <? … ?> <% … %> <script language=“php”> … </script>

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

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

  15. 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 • It produces the output on the following two slides when viewed by MSIE 6.0 and Netscape 2.0

  16. Example usage of automatic PHP variable <html> <head> <title>Your browser</title> </head> <body> <h1>Your Browser</h1> <p> You are using <?phpecho $HTTP_USER_AGENT;?> to view this page. </p> </body> </html>

  17. A warning about pre-defined variables • The way in which PHP supports pre-defined variables has changed recently. • This will be discussed in a future lecture

  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 • The programmer does not specify the type of a variable • a variable’s type is determined from the context of its usage

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

  20. 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 = -123; # a negative number $a = 0123; # octal number (equivalent to 83 decimal) $a = 0x1B; # hexadecimal number (equivalent to 27 decimal) • 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.

  21. Floating Point Numbers • These can be 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

  22. Strings • A string literal can be specified in three different ways: • single quoted • double quoted • heredoc syntax

  23. cs 3314 got here on 3 nov 2005

  24. Single-quoted Strings • In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslash • Example usage 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:\\*.*?';

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

  26. 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 • Example usage $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD;

  27. String-manipulation functions • PHP provides huge range of string-manipulation functions: • 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 • 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) • 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()

  28. get_meta_tags -- Extracts all meta tag content attributes from a file and returns an array • 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 • 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 • 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 • parse_str -- Parses the string into variables • print -- Output a string • printf -- Output a formatted string

  29. quoted_printable_decode -- Convert a quoted-printable string to an 8 bit string • quotemeta -- Quote meta characters • 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 • 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 • 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() • stripslashes -- Un-quote string quoted with addslashes()

  30. stristr -- Case-insensitive strstr() • strlen -- Get string length • strnatcmp -- String comparisons using a "natural order" algorithm • 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 • 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 • 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

  31. 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 • 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 • wordwrap -- Wraps a string to a given number of characters using a string break character. • nl_langinfo -- Query language and locale information

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

  33. Specifying 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

  34. Specifying an array (contd.) • Format of array specification array( [key =>] value, ... ) • Here is a hash array: $mothers = array (“tom"=>“mary", “mick"=>“ann", “bill"=>“orla"); • Implicit indices are integers, starting at 0 • Here is an ordinary array (indexed by integers, starting at 0): $places = array (“Cork”, “Dublin”, “Galway”);

  35. Specifying an array (contd.) • 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”);

  36. Specifying an array (contd.) • 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) );

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

  38. Array Example 2 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris', ‘Ireland'=>'Dublin'); echo "The various capitals are\n<ul>"; foreach ($capital as $city) { echo "<li>$city</li>"; }; echo "</ul>" ?> </p> </body> </html>

  39. Array Example 3 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris','Ireland'=>'Dublin'); echo "The various capitals are\n<ul>"; foreach ($capital as $country => $city) { echo "<li>The capital of $country is $city</li>"; }; echo "</ul>" ?> </p> </body> </html>

  40. Array Example 4 <html> <head> <title>Details about Fred</title> </head> <body> <h1>Details about Fred</h1> <?php $ages = array ("Fred" => 2, "Tom"=> 45); $parents = array ("Fred" => array("father" => "Tom", "mother"=>"Mary")); print "<p> Fred's age is "; print $ages["Fred"]; print ".</p>"; print "<p>His father is "; print $parents["Fred"]["father"]; print ".</p>"; ?> </body> </html>

  41. Array-manupulation functions • PHP provides a huge set of array-manipulation functions • array -- Create an array • array_change_key_case -- Returns an array with all string keys lowercased or uppercased • array_chunk -- Split an array into chunks • array_count_values -- Counts all the values of an array • array_diff -- Computes the difference of arrays • array_filter -- Filters elements of an array using a callback function • array_flip -- Flip all the values of an array • array_fill -- Fill an array with values • array_intersect -- Computes the intersection of arrays • array_key_exists -- Checks if the given key or index exists in the array • array_keys -- Return all the keys of an array • array_map -- Applies the callback to the elements of the given arrays • array_merge -- Merge two or more arrays • array_merge_recursive -- Merge two or more arrays recursively • array_multisort -- Sort multiple or multi-dimensional arrays • array_pad -- Pad array to the specified length with a value

  42. array_pop -- Pop the element off the end of array • array_push -- Push one or more elements onto the end of array • array_rand -- Pick one or more random entries out of an array • array_reverse -- Return an array with elements in reverse order • array_reduce -- Iteratively reduce the array to a single value using a callback function • array_shift -- Shift an element off the beginning of array • array_slice -- Extract a slice of the array • array_splice -- Remove a portion of the array and replace it with something else • array_sum -- Calculate the sum of values in an array. • array_unique -- Removes duplicate values from an array • array_unshift -- Prepend one or more elements to the beginning of array • array_values -- Return all the values of an array • array_walk -- Apply a user function to every member of an array • arsort -- Sort an array in reverse order and maintain index association • asort -- Sort an array and maintain index association • compact -- Create array containing variables and their values • count -- Count elements in a variable • current -- Return the current element in an array

  43. each -- Return the current key and value pair from an array and advance the array cursor • end -- Set the internal pointer of an array to its last element • extract -- Import variables into the current symbol table from an array • in_array -- Return TRUE if a value exists in an array • array_search -- Searches the array for a given value and returns the corresponding key if successful • key -- Fetch a key from an associative array • krsort -- Sort an array by key in reverse order • ksort -- Sort an array by key • list -- Assign variables as if they were an array • natsort -- Sort an array using a "natural order" algorithm • natcasesort -- Sort an array using a case insensitive "natural order" algorithm • next -- Advance the internal array pointer of an array • pos -- Get the current element from an array • prev -- Rewind the internal array pointer • range -- Create an array containing a range of elements • reset -- Set the internal pointer of an array to its first element