1 / 38

CHAPTER 9 INTRODUCTION TO PHP

1. CHAPTER 9 INTRODUCTION TO PHP. 2. ORIGINS AND USES OF PHP. Origins Rasmus Lerdorf – 1994 Developed to allow him to track visitors to his Web site PHP is an open-source product PHP is an acronym for Personal Home Page, or PHP: Hypertext Preprocessor

zola
Télécharger la présentation

CHAPTER 9 INTRODUCTION TO 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. 1 CHAPTER 9INTRODUCTION TO PHP

  2. 2 ORIGINS AND USES OF PHP • Origins • Rasmus Lerdorf – 1994 • Developed to allow him to track visitors to his Web site • PHP is an open-source product • PHP is an acronym for Personal Home Page, or PHP: Hypertext Preprocessor • PHP is used for form handling, file processing, and database access

  3. 3 OVERVIEW OF PHP • PHP is a server-side scripting language, like ASP • PHP scripts are executed on the server • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) • PHP is an open source software (OSS) • PHP is free to download and use • What is a PHP File? • PHP files may contain text, HTML tags and scripts • PHP files are returned to the browser as plain HTML • PHP files have a file extension of ".php", ".php3", or ".phtml" • PHP runs on different platforms (Windows, Linux, Unix, etc.) • PHP is compatible with almost all servers used today (Apache, IIS, etc.) • PHP is FREE to download from the official PHP resource: www.php.net

  4. What Can PHP Do? • Query a database • Allow users to upload files • Create/read files on the server (for example, the files that your users upload) • Have a "member's area" (i.e. via a login page) • Have a shopping cart

  5. Client Server URL HTML How PHP works ? • PHP is a server-side language that means the code written in PHP resides on a host computer called a server. The server sends Web pages to the requesting visitors (you, the client, with your web browser) PHP Client-Server 1 2 3 Script request Visitor goes to a web site written in PHP HTML 1 PHP Server reads the PHP and then processes it according to its scripted directions. 2 3 PHP code tells the server to send the appropriate data – HTML code. Treats it as a standard HTML.

  6. What you will need? • A web server application (Apache, Xitami, or IIS) • PHP • My SQL • Web Browser • Text editor, PHP-capable WYSIWYG application (Adobe Dreamweaver/Kompozer/Amaya) or IDE (integrated development environment) • FTP application if using remote server

  7. PHP Installation • You need to install web server before you install PHP. There are many different web servers available to choose from, so you need to choose which one you prefer. Two of the more popular web servers are: • Apache • Internet Information Services (IIS)

  8. PHP Syntax • The PHP syntax is based on C, Java, and Perl, Creating a PHP file is similar to creating an HTML file. In fact, most PHP files are a mixture of PHP code and HTML. • To create a PHP file, simply do the following: • 1. Create a new file in your favorite editor • 2. Type some PHP code • 3. Save the file with a .php extension

  9. Basic Code Syntax 3 different forms declaring php <html> <head> <title>PHP Syntax Example</title> </head> <body> <?php echo "PHP is easy!"; ?> </body> </html> <? PHP Code In Here ?> <?php PHP Code In Here php?> <script language="php"> PHP Code In Here </script>

  10. echo and print • Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty. • Expression. print() behaves like a function in that you can do: $ret = print "Hello World"; And $ret will be 1. That means that print can be used as part of a more complex expression where echo cannot. An example from the PHP Manual:

  11. echo and print echo without parentheses can take multiple parameters, which get concatenated: echo "and a ", 1, 2, 3; // comma-separated without parentheses echo ("and a 123"); // just one parameter with parentheses print()can only take one parameter: print ("and a 123"); print"and a 123";

  12. Comments in PHP PHP support three kinds of comment tags : 1. // This is a one line comment 2. # This is a Unix shell-style comment. It's also a one line comment 3. /* ..... */ Use this multi line comment if you need to.

  13. Comments in PHP <html> <body> <?php //This is a comment /* This is a comment block */?> </body> </html>

  14. Variables • Variables are used for storing values, like text strings, numbers or arrays. • When a variable is declared, it can be used over and over again in your script. • All variables in PHP start with a $ sign symbol. • The correct way of declaring a variable in PHP: • $var_name = value;

  15. String Variables in PHP String variables are used for values that contains characters. <?php $txt="Hello World"; echo $txt; ?>

  16. PHP Variables • In PHP, variable names must start with a dollar sign ($). For example: <?php $myVariable = "PHP is easy!"; echo $myVariable; ?>

  17. Variables name • Variable names can only contain alpha-numeric characters and underscores ( i.e. a-z, A-Z, 0-9, or _ ) • Variable names must not contain spaces. For multi-word variable names, either separate the words with an underscore ( _ ) or use capitalization.

  18. PHP Variables <?php $variable1 = 2; $variable2 = 9; $variable3 = $variable1 + $variable2; echo $variable3; ?>

  19. PHP Variables-Concatenation <?php $variable1 = 2; $variable2 = 9; $variable3 = $variable1 + $variable2; echo $variable1 . " + " . $variable2 . " = " . $variable3; ?>

  20. 20 PRIMITIVES, OPERATIONS, EXPRESSIONS • Variables • There are no type declarations • An unassigned (unbound) variable has the value, NULL • The unset function sets a variable to NULL • The IsSet function is used to determine whether a variable is NULL - error_reporting(15); - prevents PHP from using unbound variables • PHP has many predefined variables, including the environment variables of the host operating system • You can get a list of the predefined variables by calling phpinfo() in a script • There are eight primitive types: • Four scalar types: Boolean, integer, double, and string • Two compound types: array and object • Two special types: resource and NULL

  21. 21 PRIMITIVES, OPERATIONS, EXPRESSIONS • Integer & double are typical • Strings • Characters are single bytes • String literals use single or double quotes • Single-quoted string literals • Embedded variables are NOT interpolated • Embedded escape sequences are NOT recognized • Double-quoted string literals • Embedded variables ARE interpolated • If there is a variable name in a double-quoted string but you don’t want it interpolated, it must be back slashed • Embedded escape sequences ARE recognized • For both single- and double-quoted literal strings, embedded delimiters must be back slashed

  22. 22 PRIMITIVES, OPERATIONS, EXPRESSIONS • Boolean - values are true and false (case insensitive) • 0 and "" and "0" are false; others are true • Arithmetic Operators and Expressions • Usual operators • If the result of integer division is not an integer, a double is returned • Any integer operation that results in overflow produces a double • The modulus operator coerces its operands to integer, if necessary • When a double is rounded to an integer, the rounding is always towards zero • Arithmetic functions • floor, ceil, round, abs, min, max, rand, etc. • String Operations and Functions • The only operator is period, for catenation • Indexing - $str{3} is the fourth character

  23. 23 PRIMITIVES, OPERATIONS, EXPRESSIONS • String Operations and Functions (continued) • Functions: • strlen, strcmp, strpos, substr, as in C • chop – remove whitespace from the right end • trim – remove whitespace from both ends • ltrim – remove whitespace from the left end • strtolower, strtoupper • Scalar Type Conversions • String to numeric • If the string contains an e or an E, it is converted to double; otherwise to int • If the string does not begin with a sign or a digit, zero is used • Explicit conversions – casts • e.g., (int)$total or intval($total) or settype($total, "integer")

  24. 24 PRIMITIVES, OPERATIONS, EXPRESSIONS • The type of a variable can be determined with gettype or is_type • gettype($total) - it may return "unknown“ • is_integer($total) – a predicate function

  25. 25 OUTPUTS • Output from a PHP script is HTML that is sent to the browser • HTML is sent to the browser through standard output • There are three ways to produce output: echo,print, and printf • echo and print take a string, but will coerce other values to strings echo “Test“,”None”; # More than one parameter acceptable echo("first <br />", $sum) # More than one, so ILLEGAL! print "Welcome to my site!"; # Only one printf – same like C • PHP code is placed in the body of an HTML document

  26. 26 OUTPUTS • An Example: <html> <head><title> Trivial php example </title> </head> <body> <?php print "Welcome to my Web site!"; ?> </body> </html>

  27. 27 CONTROL STATEMENTS • Control Expressions • Relational operators - same as JavaScript, (including === and !==) • Boolean operators - same as Perl (two sets, && and and, etc.) • Selection statements • if, if-else, elseif • switch - as in C • The switch expression type must be integer,double, or string • while - just like C • do-while - just like C • for- just like C • foreach- discussed later • break - in any for, foreach, while, do-while, or switch • continue - in any loop

  28. 28 CONTROL STATEMENTS • HTML can be intermingled with PHP script <?php $a = 7; $b = 7; if ($a == $b) { $a = 3 * $a; ?> <br /> At this point, $a and $b are equal <br /> So, we change $a to three times $a <?php } ?>

  29. 29 ARRAYS • Not like the arrays of any other programming language • A PHP array is a generalization of the arrays of other languages • A PHP array is really a mapping of keys to values,where the keys can be numbers (to get a traditional array) or strings (to get a hash) • Array creation • Use the array() construct, which takes one or more key => value pairs as parameters and returns an array of them • The keys are non-negative integer literals or string literals • The values can be anything $list = array(0 => "apples", 1 => "oranges", 2 => "grapes") • This is a “regular” array of strings

  30. 30 ARRAYS • If a key is omitted and there have been integer keys, the default key will be the largest current key + 1 • If a key is omitted and there have been no integer keys, 0 is the default key • If a key appears that has already appeared, the new value will overwrite the old one • Arrays can have mixed kinds of elements $list = array("make" => "Cessna","model" => "C210","year" => 1960, 3 => "sold"); $list = array(1, 3, 5, 7, 9); $list = array(5, 3 => 7, 5 => 10, "month" => "May"); $colors = array('red', 'blue', 'green', 'yellow');

  31. 31 ARRAYS • Accessing array elements – use brackets $list[4] = 7; $list["day"] = "Tuesday"; $list[] = 17; • If an element with the specified key does not exist, it is created • If the array does not exist, the array is created • The keys or values can be extracted from an array $highs = array("Mon" => 74, "Tue" => 70,"Wed" => 67, "Thu" => 62, "Fri" => 65); $days = array_keys($highs); $temps = array_values($highs); • Dealing with Arrays • An array can be deleted with unset unset($list); unset($list[4]); # No index 4 element now

  32. 32 ARRAYS • Dealing with Arrays (continued) • is_array($list) returns true if $list is a function • in_array(17, $list) returns true if 17 is an element of $list • explode(" ", $str) creates an array with the values of the words from $str, split on a space • implode(" ", $list) creates a string of the elements from $list, separated by a space • Sequential access to array elements • current and next $colors = array("Blue", "red", "green","yellow"); $color = current($colors); print("$color <br />"); while ($color = next($colors)) print ("$color <br />");

  33. 33 ARRAYS • This does not always work – for example, if the value in the array happens to be FALSE • Alternative: each, instead of next while ($element = next($colors)) { print ("$element['value'] <br />"); • The prev function moves current backwards array_push($list, $element) and array_pop($list) • Used to implement stacks in arrays • foreach (array_name as scalar_name) { ... } foreach ($colors as $color) {print "Is $color your favorite?<br /> ";} Is red your favorite color Is blue your favorite color Is green your favorite color? Is yellow your favorite color?

  34. 34 ARRAYS • foreach can iterate through both keys and values: foreach (array as key => value) { … } • Inside the compound statement, both $key and $color are defined $ages = array("Bob" => 42, "Mary" => 43); foreach ($ages as $name => $age) print("$name is $age years old <br />");

  35. 35 PHP EXAMPLES • To concatenate two or more variables together, use the dot (.) operator: <html> <body><?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2 ; ?></body> </html> • The output of the script above will be: "Hello World 1234"

  36. 36 PHP EXAMPLES • The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body><?php $d=date("D"); if ($d =="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?></body> </html>

  37. 37 PHP EXAMPLES • The following example prints the text "Hello World!" five times: <html> <body><?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?></body> </html>

  38. 38 PHP EXAMPLES • The following example demonstrates a loop that will print the values of the given array: <html> <body><?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?></body> </html>

More Related