1 / 81

Developing Web Applications with PHP

Developing Web Applications with PHP. RAD for the World Wide Web. Introduction. Netcraft Statistics 20,917,850 domains, 1,224,183 IP addresses. Programming Language Popularity. Introduction. What is PHP? PHP stands for "PHP Hypertext Preprocessor”

nancys
Télécharger la présentation

Developing Web Applications with 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. Developing Web Applications with PHP RAD for the World Wide Web

  2. Introduction • Netcraft Statistics • 20,917,850 domains, 1,224,183 IP addresses

  3. Programming Language Popularity

  4. Introduction • What is PHP? • PHP stands for "PHP Hypertext Preprocessor” • An embedded scripting language for HTML like ASP or JSP • A language that combines elements of Perl, C, and Java

  5. Introduction • History of PHP • Created by Rasmus Lerdorf in 1995 for tracking access to his resume • Originally a set of Perl scripts known as the “Personal Home Page” tools • Rewritten in C with database functionality • Rewritten again in and released as version 2.0 in November of 1997

  6. Introduction • History of PHP (cont.) • Rewritten again in 1997 by Andi Gutmans and Zeev Suraski – OOP features • More functionality added, database support, protocols and APIs • The core is rewritten in 1998 by Zeev and Andi and dubbed the “Zend Engine” • Version 4.0 released in 2000

  7. Introduction • History of PHP (cont.) • Version 5.0 includes version 2.0 of the Zend Engine • New object model is more powerful and intuitive • Objects are no longer passed by value; they now are passed by reference • Increases performance and makes OOP more attractive

  8. Introduction • Performance* • Zdnet Statistics • PHP  about 47 pages/second • Microsoft ASP  about 43 pages/second • Allaire ColdFusion  about 29 pages/second • Sun Java JSP  about 13 pages/second* From PHP HOWTO, July 2001

  9. PHP Language Basics • The Script Tags • All PHP code is contained in one of several script tags: • <?// Some code?> • <?php// Some code here// This is the preferred method ?>

  10. PHP Language Basics • The Script Tags (cont.) • <script language=“PHP"> // Some code here</script> • ASP-style tags • Introduced in 3.0; may be removed in the future • <% // Some code here%>

  11. PHP Language Basics • The Script Tags (cont.) • “Echo” Tags • <table><tr> <td>Name:</td><td><?= $name ?></td></tr><tr> <td>Address:</td><td><?= $address ?></td></tr></table>

  12. PHP Language Basics • Hello World!: An Example • Like Perl, there is more than one way • <?php echo “Hello World!”; ?> • <?php $greeting = “Hello World!” printf(“%s”, $greeting);php?> • <script language=“PHP”> $hello = “Hello”; $world = “World!”; print $hello . $world</script>

  13. PHP Language Elements Variables start with $ followed by name name must start with _ or alphabetic name can contain _ or alphanumeric Operators Arithmetic + - * / % Assignment = += -= Bitwise \& | ^ ~ << >> Comparison == != < > <= >= Logical and or xor ! && ||

  14. PHP Language Basics • Constants, Data Types and Variables • Constants define a string or numeric value • Constants do not begin with a dollar sign • Examples: • define(“COMPANY”, “Acme Enterprises”); • define(“YELLOW”, “#FFFF00”); • define(“PI”, 3.14); • define(“NL”, “<br>\n”); • Using a constant • print(“Company name: “ . COMPANY . NL);

  15. PHP Language Basics • Constants, Data Types and Variables • Data types • Integers, doubles and strings • isValid = true; // Boolean • 25 // Integer • 3.14 // Double • ‘Four’ // String • “Total value” // Another string

  16. PHP Language Basics • Constants, Data Types and Variables • Data types • Strings and type conversion • $street = 123; • $street = $street . “ Main Street”; • $city = ‘Naperville’;$state = ‘IL’; • $address = $street; • $address = $address . NL . “$city, $state”; • $number = $address + 1; // $number equals 124

  17. PHP Language Basics • Constants, Data Types and Variables • Data types • Arrays • Perl-like syntax for hashes • $arr = array("foo" => "bar", 12 => true); • same as • $arr[“foo”] = “bar”; • $arr[12] = true;

  18. PHP Language Basics • Constants, Data Types and Variables • Arrays (cont.) • <?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42?>

  19. PHP Language Elements Statements terminated by a semicolon (;) or the closing PHP tag. compound statements enclosed in braces { } Comments C /* */ , C++ //….. and shell style # Types array, boolean, floating-point, integer, string, object arrays behave as hash tables var[1] = 36.7; var[“my name”] = “Marianne Brown”; key needs to be either an integer or string value can be anything

  20. PHP: Control Structures if-then-else if (expr) { stmt; } elseif (expr) { stmt; } else { stmt; }

  21. PHP: Control Structures while loop while (expr) { stmt; } do-while loop do { stmt; } while (expr);

  22. PHP: Control Structures for loop for (expr1; expr2; expr3) { stmt; } switch statement switch (expr) { case 0: stmt; break; case 1: case 2: stmt; break; default: stmt; }

  23. PHP: Functions The function keyword declares a function. function square($num) { return $num * $num; } echo square(4); // outputs ‘16’

  24. Functions function add($a, $b) { return $a + $b; } function swap(&$a, &$b) { $c = $a; $a = $b; $b = $a } $count = 0; function inc() { global $count; $count++; }

  25. PHP: Functions header(): send http header to client setcookie(): send cookie to client mail(): send email from php dns_get_mx(): check mail exchange record connection_status(): check connection status, e.g. abort, timeout gethostbyname(): get IP address of host ftp functions: ftp_connect(), ftp_login(), ftp_fget(), ftp_fput(), …

  26. PHP: Classes class Cart { var $todays_date; var $name; var $owner; function Cart() { $this->todays_date = date(“Y-m-d”); } function addItem($code, $descript, $qty) { /* stuff */ } } $cart = new Cart; $cart->addItem(“002564”,”1kg Tin Beans”, 10);

  27. FORM Handling • GET • $_GET['name'] • POST • $_POST['name'] • or just use the more general method • $_REQUEST[‘name’]

  28. FORM Example <form action="test.php" method="post"> <table> <tr> <th>Name:</th> <td><input type="text" name="name"></td> </tr> <tr> <th>Age:</th> <td><input type="text" name="age"></td> </tr> </table> </form> <p>Hello <?=$_POST['name']?>. You are <?=$_POST['age']?> years old.</p>

  29. Session • Start session - session_start() • Need to call before output • If session has started already, load registered session variables. Otherwise, create a new session. • Uses cookies to identify session (PHPSESSID) • Session variables stored on server • $_SESSION[‘name’] =value • isset($_SESSION[‘name’]) • session_destroy()

  30. PHP Include • Universal header and footer • Create a file called header.php. This file will have all of theheader HTML code. You can use FrontPage/Dreamweaver to create the header, but remember to remove the closing </BODY> and </HTML> tags.

  31. PHP Include • Universal header and footer • Next, create a file called footer.php. This file will have all of the footer HTML code.

  32. PHP Include • Universal header and footer • This is the basic template that you will use on all of the pages. Make sure you name the files with a .php extension so that the server will process the PHP code. In this example, we assume the header and footer files are located in the same directory.

  33. What comes In the box? Array Manipulator Functions sort, merge, push, pop, slice, splice, keys, count $keysarray = array_keys($somearray); asort($somearray); // sorts - preserves associations String Manipulation Functions Strlen, trim, substr, ucfirst, ucwords, strtolower, strtoupper, strstr, strcasecmp, strtok, str_replace, explode, implode, join - array/string transformations Date and Time Functions getdate, mkdate, date, gettimeofday, localtime, strtotime, time Built-in Functions

  34. Built-in Functions • What comes In the box? • Directory Functions • Platform independent • Error Handling Functions • Recover from warnings and errors • Filesystem Functions • Access flat files • Check directory, link, and file status information • Copy, delete, and rename files

  35. Built-in Functions • Regular Expressions • Regular expression syntax identical to PERL • Functions • preg_match(pattern, string[, matches]) • preg_match_all(pattern, string) • preg_replace(pattern, replacement, string) • $array = preg_split(pattern, string)

  36. Regex Example <html> <head><title>Regex in PHP</title></head> <body> <h1>Using Regex in PHP</h1> <?php $test = "cookies::multipack::chocolate::brownies"; $parts = preg_split("/::/", $test); echo "<ul>"; while (list($key, $val) = each($parts)) { echo "<li>$key = $val</li>"; } echo "</ul>"; ?> </body> </html>

  37. Built-in Functions • What comes In the box? • IMAP Functions • Manipulate mail boxes via the IMAP protocol • LDAP Functions • Works with most LDAP servers • Mail Functions • mail($recipient, $subject, $message) • CCVS: Interface to Red Hat’s credit system

  38. Built-in Functions • What comes In the box? • Database Functions • dba: dbm-style abstraction layer • dBase • Frontbase • Informix • Ingres II • Interbase • mSQL

  39. Built-in Functions • What comes In the box? • Database Functions (cont.) • MySQL • Oracle • PostgreSQL • SQL Server • MING • Macromedia Flash • PDF • Create/manipulate PDF files dynamically

  40. <?php class DAO { private $link; private $db; public function __construct($host, $dbname) { $link = mysql_connect($host); $db = mysql_select_db($dbname, $link); if (!$db) { die("Unable to connect to database\n"); } } public function getPeople() { $query = "select * from QuinnsTable"; if ($result = mysql_query($query)) { $i = 0; while ($data = mysql_fetch_object($result)) { $people[$i] = $data; $i++; } return $people; } else { // Check result. This shows the actual query sent to MySQL, and the error. Useful for debugging. $message = 'Invalid query: ' . mysql_error() . "\n” . 'Whole query: ' . $query; die($message); } } } ?>

  41. Built-in Functions • What comes In the box? • POSIX Functions • Manipulate process information • Semaphore and Socket Functions • Available only on Unix • Session Management Functions

  42. Numeric Value Validation • All data passed to PHP (GET/POST/COOKIE) ends up being a string. Using strings where integers are needed is not only inefficient but also dangerous. // integer validation if (!empty($_GET['id'])) { $id = (int) $_GET['id']; } else $id = 0; // floating point number validation if (!empty($_GET['price'])) { $price = (float) $_GET['price']; } else $price = 0; • Casting is a simple and very efficient way to ensure variables do in fact contain numeric values. Security

  43. Validating Strings • PHP comes with a ctype, extension that offers a very quick mechanism for validating string content. if (!ctype_alnum($_GET['login'])) { echo "Only A-Za-z0-9 are allowed."; } if (!ctype_alpha($_GET['captcha'])) { echo "Only A-Za-z are allowed."; } if (!ctype_xdigit($_GET['color'])) { echo "Only hexadecimal values are allowed"; } Security

  44. Path Validation • Values passed to PHP applications are often used to specify what file to open. This too needs to be validated to prevent arbitrary file access. http://example.com/script.php?path=../../etc/passwd <?php $fp = fopen(“/home/dir/{$_GET[‘path’]}”, “r”); ?> Security

  45. Path Validation • PHP includes a basename() function that will process a path and remove everything other than the last component of the path, usually a file name. <?php $_GET[‘path’] = basename($_GET[‘path’]); // only open a file if it exists. if (file_exists(“/home/dir/{$_GET[‘path’]}”)) { $fp = fopen(“/home/dir/{$_GET[‘path’]}”, “r”); } ?> Security

  46. XSS • Cross Site Scripting (XSS) is a situation where an attacker injects HTML code, which is then displayed on the page without further validation. • Can lead to embarrassment. • Session take-over. • Password theft. • User tracking by 3rd parties. Security

  47. Preventing XSS • Prevention of XSS can be as simple as filtering input data via one of the following: • htmlspecialchars() • Encodes ‘, “, <, >, & • htmlentities() • Convert anything that there is HTML entity for. • strip_tags() • Strips anything that resembles HTML tag. Security

  48. Preventing XSS $str = strip_tags($_POST['message']); // encode any foreign & special chars $str = htmlentities($str); // maintain new lines, by converting them to <br /> echo nl2br($str); // strip tags can be told to "keep" certain tags $str = strip_tags($_POST['message'], '<b><p><i><u>'); $str = htmlentities($str); echo nl2br($str); • Tag allowances in strip_tags() are dangerous, because attributes of those tags are not being validated in any way. Security

  49. Tag Allowance Problems <b style="font-size: 500px"> TAKE UP ENTIRE SCREEN </b> <u onmouseover="alert('JavaScript is allowed');"> <b style="font-size: 500px">Lot's of text</b> </u> <p style="background: url(http://tracker.com/image.gif)"> Let's track users </p> Security

  50. Error Reporting • By default PHP will print all errors to screen, startling your users and in some cases disclosing privileged information. • File paths. • Un-initialized variables. • Sensitive function arguments such as passwords. • At the same time, disabling error reporting would make bug tracking near impossible. Security

More Related