Phát triển ứng dụng mã nguồn mở - Bài 2.2: Fundamentals of PHP

• Tổng quan về PHP. • Công cụ lập trình với PHP. • Ngôn ngữ lập trình PHP. – Khái niệm cơ bản – Hàm xuất dữ liệu. – Mãng – Hàm

pdf98 trang | Chia sẻ: thuychi16 | Lượt xem: 797 | Lượt tải: 1download
Bạn đang xem trước 20 trang tài liệu Phát triển ứng dụng mã nguồn mở - Bài 2.2: Fundamentals of PHP, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Đoàn Thiện Ngân Bài 2.2 - 1/98 Bài 2.2: Fundamentals of PHP GV: ĐOÀN THIỆN NGÂN Đoàn Thiện Ngân Bài 2.2 - 2/98 Nội dung • Tổng quan về PHP. • Công cụ lập trình với PHP. • Ngôn ngữ lập trình PHP. – Khái niệm cơ bản – Hàm xuất dữ liệu. – Mãng – Hàm Đoàn Thiện Ngân Bài 2.2 - 3/98 Tài liệu tham khảo 1. Bắt buộc: PHP Manual. 2. Beginning PHP and MySQL: From Novice to Professional, 4th Edition, W. Jason Gilmore, 2010 3. PHP for the Web; 4th Edition, Larry Ullman; Peachpit Press; 2011. Đoàn Thiện Ngân Bài 2.2 - 4/98 General Concepts • PHP (Hypertext Preprocessor): ngôn ngữ scripting mã nguồn mở được nhiều người sử dụng đặc biệt phù hợp với ứng dụng web và dễ dàng nhúng vào HTML. • PHP code sử dụng các lệnh nằm trong cặp tag • PHP khác hẵn với client-side JavaScript: – Mã lệnh PHP được thực hiện tại server, – Khi PHP script thực hiện xong, mã HTML phát sinh được gởi về client – PHP là ngôn ngữ server−side scripting. Đoàn Thiện Ngân Bài 2.2 - 5/98 PHP scripts PHP scripts được dùng trong 3 lãnh vực: • Server-side scripting: lãnh vực chính và phổ biến nhất của PHP (CGI or server module). • Command line scripting: PHP script có thể chạy như shell script không cần server hay browser. Lý tưởng cho scripts dùng cron (on *nix or Linux) hay Task Scheduler (on Windows) ─ simple text processing tasks. • Writing desktop applications: PHP không phải là ngôn ngữ tốt tạo ứng dụng GUI desktop, nhưng có thể dùng PHP-GTK để viết chương trình như thế. Đoàn Thiện Ngân Bài 2.2 - 6/98 PHP Characteristics • PHP có thể được dùng trên hầu hết các OS: Linux, Unix (HP-UX, Solaris, OpenBSD, ), MS Windows, Mac OS X, RISC OS, • PHP cũng hỗ trợ hầu hết web servers: IIS, Apache, PHP có thể hoạt động như module, hay như CGI processor. • Không chỉ có output HTML, PHPcó khả năng xuất dữ liệu dạng images, PDF và ngay cả Flash movies (libswf & Ming), XHTML, XML, • PHP có thể tạo ra các tập tin và lưu trữ trong hệ thống tập tin. PHP có thể tạo dữ liệu trong bộ nhớ đệm trên server. Đoàn Thiện Ngân Bài 2.2 - 7/98 PHP Characteristics • Một tính năng mạnh nhất và ấn tượng nhất là sự hỗ trợ hầu hết các DBMS: MySQL, PostGreSQL, Sybase, MS SQL Server, • Trong PHP, viết trang web truy cập DBMS có thể dùng những specific extensions (mysql, mysqli, pgsql, ), hay dùng abstraction layer như PDO (PHP Data Object), hay giao tiếp với các DBMS hỗ trợ Open Database Connection chuẩn (ODBC extension). DBMS khác có thể dùng sockets (CouchDB). Đoàn Thiện Ngân Bài 2.2 - 8/98 PHP Download. • • • • Môi trường cài đặt: – MS Windows – Linux – Unix – Mac OS – Đoàn Thiện Ngân Bài 2.2 - 9/98 PHP – Apache – MS Windows • Trước hết cần web server: Apache, IIS, • MS Windows: 1. Cài từng phần riêng lẻ (đọc PHP manual) a) httpd b) php, cấu hình php với Apache, thử chạy trang php 2. Cài gói cấu hình sẵn (đơn giản) – Wamp, AppServ, xampp, (Windows, Apache, MySQL, PHP) Đoàn Thiện Ngân Bài 2.2 - 10/98 PHP – Apache – Linux • Gói LAMP • Cài riêng lẻ – Cài httpd (Apache server) # yum install httpd httpd–manual # service httpd start # chkconfig ––levels 235 httpd on (thử Firefox –– localhost) – Cài php # yum install php php–mysqlnd php–pgsql php–pdo # service httpd restart – Thử nghiệm php Đoàn Thiện Ngân Bài 2.2 - 11/98 Linux – PHP – Apache 2.x • Dùng trình soạn thảo thử tạo info.php trong thư mục webroot mặc định: /var/www/html. <?php phpinfo(); ?> • Mở trình duyệt Firefox thử trang info.php Đoàn Thiện Ngân Bài 2.2 - 12/98 Trình soạn thảo PHP • Netbeans • EclipsePHP • Dreamweaver CS • Zend Studio • Aptana, Bluefish, PsPAD, Đoàn Thiện Ngân Bài 2.2 - 13/98 PHP Basics • Embedding PHP Code in Your Web Pages • Commenting Your Code – Single-Line C++ Syntax: // – Shell Syntax: # – Multiple-Line C Syntax: /* */ • Outputting Data to the Browser – print() Statement – echo() Statement – printf() Statement – sprintf() Statement – print_r() Statement Đoàn Thiện Ngân Bài 2.2 - 14/98 PHP Identifiers • Identifier is a general term applied to variables, functions, and various other user-defined objects. • An identifier can consist of one or more characters and must begin with a letter or an underscore. Furthermore, identifiers can consist of only letters, numbers, underscore characters, and other ASCII characters from 127 through 255. • Identifiers are case sensitive. A variable named $recipe is different from a variable named $Recipe, $rEciPe, or $recipE. Đoàn Thiện Ngân Bài 2.2 - 15/98 PHP Identifiers • Identifiers can be any length. This is advantageous because it enables a programmer to accurately describe the identifier’s purpose via the identifier name. • An identifier name can’t be identical to any of PHP’s predefined keywords. • You can find a complete list of these keywords in the PHP manual appendix. Đoàn Thiện Ngân Bài 2.2 - 16/98 PHP Variables • A variable is a symbol that can store different values at different times. • A variable is a named memory location that contains data and may be manipulated throughout the execution of the program. • Variable Declaration: A variable always begins with a dollar sign ─ $, which is then followed by the variable name. • Variable name can begin with either a letter or an underscore and can consist of letters, underscores, numbers, or other ASCII characters ranging from 127 through 255. Đoàn Thiện Ngân Bài 2.2 - 17/98 PHP Variables • Note that variables are case sensitive • Rather, variables can be declared and assigned values simultaneously. • Value Assignment: Assignment by value simply involves copying the value of the assigned expression to the variable assignee. $color = "red"; $number = 12; $age = 12; $sum = 12 + "15"; // $sum = 27 Đoàn Thiện Ngân Bài 2.2 - 18/98 PHP Variables • Reference Assignment: you can create a variable that refers to the same content as another variable does. Therefore, a change to any variable referencing a particular item of variable content will be reflected among all other variables referencing that same content. You can assign variables by reference by appending an ampersand (&) to the equal sign (=&) or (= &$...). $value1 = "Hello"; $value2 =& $value1; (or $value2 = &$value1; ) // $value1 and $value2 both equal "Hello" $value2 = "Goodbye"; // $value1 and $value2 both equal "Goodbye" Đoàn Thiện Ngân Bài 2.2 - 19/98 Variable Scope • The location of the declaration greatly influences the realm in which a variable can be accessed, however. This accessibility domain is known as its scope. • PHP variables can be one of 4 scope types: – Local variables – Function parameters – Global variables – Static variables Đoàn Thiện Ngân Bài 2.2 - 20/98 Local variables • A variable declared in a function is considered local. $x = 4; function assignx () { $x = 0; printf("\$x inside function is %d ", $x); } assignx(); printf("\$x outside of function is %d ", $x); Đoàn Thiện Ngân Bài 2.2 - 21/98 Function Parameters • This section applies only to parameters passed by value and not to those passed by reference. • Parameters passed by reference will indeed be affected by any changes made to the parameter from within the function. • } function squarex ($value) { $value = $value * $value; return $value } Đoàn Thiện Ngân Bài 2.2 - 22/98 Global Variables • In contrast to local variables, a global variable can be accessed in any part of the program. $somevar = 15; function addit() { global $somevar; $somevar++; echo “somevar is $somevar"; } addit(); Đoàn Thiện Ngân Bài 2.2 - 23/98 Global Variables • An alternative method for declaring a variable to be global is to use PHP’s $GLOBALS array. $somevar = 15; function addit() { $GLOBALS["somevar"]++; } addit(); Đoàn Thiện Ngân Bài 2.2 - 24/98 Static Variables • In contrast to the variables declared as function parameters, which are destroyed on the function’s exit, a static variable does not lose its value when the function exits and will still hold that value if the function is called again. • You can declare a variable as static simply by placing the keyword static in front of the variable name, static $count = 0; Đoàn Thiện Ngân Bài 2.2 - 25/98 PHP’s Superglobal Variables • PHP offers a number of useful predefined variables (accessible from anywhere, specific to the OS and web server) • These variables: to retrieve details about the current user session, the user’s operating environment, the local operating environment, and more. • The following code will output all predefined variables pertinent to any given web server and the script’s execution environment: foreach ($_SERVER as $var => $value) { echo "$var => $value "; } Đoàn Thiện Ngân Bài 2.2 - 26/98 Predefined Variables ─ 1 • Superglobals —are built-in variables that are always available in all scopes • $GLOBALS all variables available in global scope • $_GET HTTP GET variables • $_POST HTTP POST variables • $_FILES HTTP File Upload variables • $_REQUEST HTTP Request variables • $_ENV Environment variables Đoàn Thiện Ngân Bài 2.2 - 27/98 Predefined Variables ─ 2 • $_SERVER Server & execution environment information • $_COOKIE HTTP Cookies • $_SESSION Session variables • $php_errormsg The previous error message • $HTTP_RAW_POST_DATA Raw POST data • $http_response_header HTTP response headers • $argc The number of arguments passed to script • $argv Array of arguments passed to script Đoàn Thiện Ngân Bài 2.2 - 28/98 PHP’s Supported Data Types • Scalar Data Types: are used to represent a single value. Several data types fall under this category including boolean, integer, float, and string. – Boolean: false (= 0), true (≠ 0) – Integer: values represented in base10 (42 - decimal), base8 (015 - octal), and base16 (0xC4F - hexadecimal) numbering systems. – Float: floats, doubles, real numbers – String: sequence of characters treated as a contiguous group. Strings are delimited by single or double quotes. Đoàn Thiện Ngân Bài 2.2 - 29/98 PHP’s Supported Data Types • Compound Data Types: allow for multiple items of the same type to be aggregated under a single representative entity. The array and the object fall into this category. – Object: The object is a central concept of the OOP paradigm. Unlike the other data types contained in the PHP language, an object must be explicitly declared (class). Đoàn Thiện Ngân Bài 2.2 - 30/98 PHP’s Supported Data Types Array – Array: a series of similar items together, arranging and referencing them in some specific way (an indexed collection of data values). Each member of the array index (also known as the key) references a corresponding value and can be a simple numerical reference to the value’s position in the series, or it could have some direct correlation to the value. Output function: print_r() Đoàn Thiện Ngân Bài 2.2 - 31/98 Output Data to the Browser • print: int print(argument) print("I love the summertime."); print "I love the $season."; • echo: void echo(string argument1 [, ..., string argumentN]) echo "I love the summertime."; • printf: integer printf(string format [, mixed args]) printf("Bar inventory: %d bottles of tonic water.", 100); printf("%d bottles of tonic water cost $%f", 100, 43.20); Đoàn Thiện Ngân Bài 2.2 - 32/98 Output Data to the Browser – The printf() statement is ideal when you want to output a blend of static text and dynamic information stored within one or several variables. – sprintf: string sprintf(string format [, mixed arguments]) $cost = sprintf("$%.2f", 43.2); // $cost = $43.20 The sprintf() statement is functionally identical to printf() except that the output is assigned to a string rather than rendered to the browser. Đoàn Thiện Ngân Bài 2.2 - 33/98 Expression • Expression: a phrase representing a particular action in a program. All expressions consist of at least one operand and one or more operators. • Operands: the inputs of an expression. $a++; // $a is the operand $sum = $val1 + $val2; // $sum, $val1 and $val2 are operands • Operator : a symbol that specifies a particular action in an expression. Many operators may be familiar to you. • You should remember that PHP’s automatic type conversion will convert types based on the type of operator placed between the two operands. Đoàn Thiện Ngân Bài 2.2 - 34/98 The include() Statement • include() statement will evaluate and include a file into the location where it is called. • Including a file produces the same result as copying the data from the file specified into the location in which the statement appears. • Like the print and echo statements, you have the option of omitting the parentheses when using include() include(/path/to/filename) include "/var/www/html/php/config.inc.php"; Đoàn Thiện Ngân Bài 2.2 - 35/98 Requiring a File • require() operates like include(), including a template into the file in which the require() call is located. • There are two important differences between require() and include(). Đoàn Thiện Ngân Bài 2.2 - 36/98 Requiring a File • First, the file will be included in the script in which the require() construct appears, regardless of where require() is located. For instance, if require() is placed within an if statement that evaluates to false, the file would be included anyway. • The second important difference is that script execution will stop if a require() fails, whereas it may continue in the case of an include(). • One possible explanation for the failure of a require() statement is an incorrectly referenced target path. require (filename) Đoàn Thiện Ngân Bài 2.2 - 37/98 include_once & require_once • The include_once() function has the same purpose as include() except that it first verifies whether the file has already been included. • As your site grows, you may find yourself redundantly including certain files. Although this might not always be a problem, sometimes you will not want modified variables in the included file to be overwritten by a later inclusion of the same file. Another problem that arises is the clashing of function names should they exist in the inclusion file. You can solve these problems with the require_once() function. Đoàn Thiện Ngân Bài 2.2 - 38/98 String Interpolation Double Quotes • Strings enclosed in double quotes are the most commonly used in PHP scripts because they offer the most flexibility. This is because both variables and escape sequences will be parsed accordingly. Ex: $sport = "boxing"; echo "Jason's favorite sport is $sport."; // Jason's favorite sport is boxing. Đoàn Thiện Ngân Bài 2.2 - 39/98 String Interpolation Escape Sequences • Escape sequences are also parsed. Ex: $output = "This is one line.\nAnd this is another line."; echo $output; /* This is one line. And this is another line. */ Đoàn Thiện Ngân Bài 2.2 - 40/98 String Interpolation Single Quotes • Enclosing a string within single quotes is useful when the string should be interpreted exactly as stated. This means that both variables and escape sequences will not be interpreted when the string is parsed. Ex: print 'This string will $print exactly as it\'s \n declared.'; This string will $print exactly as it's \n declared. Đoàn Thiện Ngân Bài 2.2 - 41/98 String Interpolation Curly Braces • While PHP is perfectly capable of interpolating variables representing scalar data types, you’ll find that variables representing complex data types such as arrays or objects cannot be so easily parsed when embedded in an echo() or print() string. You can solve this issue by delimiting the variable in curly braces. echo "The capital of Ohio is {$capitals['ohio']}."; Đoàn Thiện Ngân Bài 2.2 - 42/98 Control Structures The if Statement if (expression) { statement } hay có else if (expression) { statement } else (expression) { statement } The elseif Statement if (expression) { statement } elseif (expression) { statement } else (expression) { statement } Đoàn Thiện Ngân Bài 2.2 - 43/98 The switch Statement switch($category) { case "news": echo "What's happening around the world "; break; case "weather": echo "Your weekly forecast"; break; case "sports": echo "Latest sports highlights"; break; default: echo "Welcome to my web site"; Đoàn Thiện Ngân Bài 2.2 - 44/98 The while Statement while (expression) { statements } Ex: $count = 1; while ($count < 5) { printf("%d squared = %d ", $count, pow($count, 2)); $count++; } Đoàn Thiện Ngân Bài 2.2 - 45/98 The do...while Statement do { statements } while (expression); • Both while and do...while are similar in function. • The only real difference is that the code embedded within a while statement possibly could never be executed, whereas the code embedded within a do...while statement will always execute at least once. Đoàn Thiện Ngân Bài 2.2 - 46/98 The for Statement for (expression1; expression2; expression3) { statements } • Expression1 is evaluated by default at the first iteration of the loop. • Expression2, is evaluated at the beginning of each iteration. This expression determines whether looping will continue. • Expression3, is evaluated at the conclusion of each loop. • Any of the expressions can be empty, their purpose substituted by logic embedded within the for block. Đoàn Thiện Ngân Bài 2.2 - 47/98 The foreach Statement • The foreach looping construct syntax is adept at looping through arrays, pulling each key/value pair from the array until all items have been retrieved or some other internal conditional has been met. • Two syntax variations are available. • The first syntax variant strips each value from the array, moving the pointer closer to the end with each iteration. foreach (array_expr as $value) { } Đoàn Thiện Ngân Bài 2.2 - 48/98 The foreach Statement • The second variation is well-suited for working with both the key and value of an array. foreach (array_expr as $key => $value) { } $links = array("The Apache Web Server" => "www.apache.org", "Apress" => "www.apress.com", "The PHP Scripting Language" => "www.php.net"); foreach($links as $title => $link) { echo "$title"; } Đoàn Thiện Ngân Bài 2.2 - 49/98 break – goto – continue • Encountering a break statement will immediately end execution of a do...while, for, foreach, switch, or while block. • In PHP 5.3, the break feature was extended to support labels. This means you can suddenly jump to a specific location outside of a looping or conditional construct with goto. • The continue statement causes execution of the current loop iteration to end and commence at the beginning of the next iteration. Đoàn Thiện Ngân Bài 2.2 - 50/98 What Is an Array? • An array is defined as a group of items that share certain characteristics, such as similarity (car models, baseball teams, types of fruit, etc.) and type (e.g., all strings or integers). Each item is distinguished by a special identifier known as a key. • PHP takes this definition a step further, forgoing the requirement that the items share the same data type. • For example, an array could quite possibly contain items such as state names, ZIP codes, exam scores, or playing card suits. Đoàn Thiện Ngân Bài 2.2 - 51/98 What Is an Array? • Each item consists of two components: the aforementioned key and a value. • The key serves as the lookup facility for retrieving its counterpart, the value. • Keys can be numerical or associative. Numerical keys bear n