Download presentation
Presentation is loading. Please wait.
Published byKristopher Barber Modified over 9 years ago
1
COMP 205 - Week 5 Dr. Chunbo Chu
2
Agenda 1. Brief History of PHP 2. Basics 3. Advanced
3
Brief History of PHP PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix. PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc. PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans. PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added. PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP
4
Brief History of PHP As of July 2007, PHP is used on 20,917,850 domains, 1,224,183 IP addresses. http://www.php.net/usage.php Source: Netcraft http://www.php.net/usage.phpNetcraft
5
Why is PHP used? 1.Easy to Use Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode". Example
6
echo is the common method in outputting data. Since it is a language construct, echo doesn’t require parenthesis like print(). Output Text Usage: // prints out Hello World Output the value of a PHP variable: // prints out the number of hits Echo has a shortcut syntax, but it only works with the “short open tag” configuration enabled on the server. How to output using PHP
7
Examples 3. Other uses with echo Automatically generate the year on your pages. This will print out ©2009 UC Riverside. © UC Riverside You will need to escape any quotation marks with a backslash.
8
Why is PHP used? 2.Cross Platform Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003 Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm
9
Why is PHP used? 3.Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free.
10
Server-side Script User-agent (web browser) requests a web page http request Server detects PHP code in page, executes the code, and sends the output to the user http response Web page (with PHP Output) sent to PC User never sees the PHP, only the output Cannot affect the browser or client PC
11
Getting Started 1. How to escape from HTML and enter PHP mode PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag. PHP CODE HTML
12
Start your Virtual Machine
13
Getting Started 2. Simple HTML Page with PHP The following is a basic example to output text using PHP. Copy the code onto your web server and save it as “hello.php”. Notice that the semicolon is used at the end of each line of PHP code to signify a line break. Like HTML, PHP ignores whitespace between lines of code. (An HTML equivalent is ) Semicolons are must!
14
Variables All variables in PHP start with a $ sign symbol. $var_name = value;
15
PHP: Loosely Typed A variable does not need to be declared before adding a value to it. Do not have to tell PHP which data type the variable is PHP automatically converts the variable to the correct data type, depending on its value. Compared to a strongly typed programming language..
16
Naming Rules for Variables A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)
17
PHP String Variables String variables are used for values that contains characters. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the text "Hello World" to a string variable called $txt:
18
PHP String Variables The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two string variables together, use the concatenation operator: The output: Hello World! What a nice day!
19
PHP String Variables The strlen() function is used to return the length of a string. The output: 12 The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string).
20
PHP String Variables The strpos() function is used to search for character within a string. If a match is found, this function will return the position of the first match. If no match is found, it will return FALSE. The output: 6 The position of the string "world" in our string is position 6. The reason that it is 6 (and not 7), is that the first position in the string is 0, and not 1
21
PHP Operators Arithmetic Operators
22
PHP Operators Assignment Operators
23
PHP Operators Comparison Operators
24
PHP Operators Logical Operators
25
Conditional Statements Conditional statements are very useful for displaying specific content to the user. The if Statement Use the if statement to execute some code only if a specified condition is true. if (condition) code to be executed if condition is true;
26
Conditional Statements The if...else Statement if (condition) code to be executed if condition is true; else code to be executed if condition is false; "; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?>
28
Switch Statement switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; } Don’t forget break!
30
Array An array is a special variable, which can hold more than one value, at a time. $cars1="Saab"; $cars2="Volvo"; $cars3="BMW"; An array can hold all your variable values under a single name Three kinds of arrays: Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays
31
Numeric Arrays Numeric index $cars=array("Saab","Volvo","BMW","Toyota"); $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0]. " and ". $cars[1]. " are Swedish cars."
32
Associative Arrays When storing data about specific named values, a numerical array is not always the best way to do it. Each ID key is associated with a value. We can use the values as keys and assign values to them. $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
33
A different way
34
Multidimensional Arrays Each element in the main array can also be an array. Each element in the sub-array can be an array, and so on. $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
35
echo "Is ". $families['Griffin'][2]. " a part of the Griffin family?"; The code above will output: Is Megan a part of the Griffin family?
36
Looping The same block of code to run over and over again Looping statements: while - loops through a block of code while a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array
37
while "; $i++; } ?>
38
do...while "; } while ($i
39
for for (init; condition; increment) { code to be executed; } Parameters: init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)
40
for "; } ?>
41
foreach "; } ?>
42
Activity Implement the following table in a multi-dimensional array "student“: Output the student table in form of a table. NameIDGrade Tom000198 John000581 Jane000670
43
<?php $student=array( array("Tom","001", "98"), array("John","002", "81"), array("Jane", "003", "67") ); echo " Name ID Score "; foreach ($student as $person) { echo " "; foreach ($person as $x) echo " ". $x." "; echo " "; } echo " "; ?>
44
Functions The real power of PHP: more than 700 built-in functions. To keep the browser from executing a script when the page loads, you can put your script into a function. A function will be executed by a call to the function. You may call a function from anywhere within a page.
45
Create a PHP Function A function will be executed by a call to the function. function functionName() { code to be executed; }
46
Adding parameters "; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?>
47
Return values
48
Activity Implement the following functions for the student table: A “grade($score)" function that convert a numeric score into a letter grade: $score >=90 A $score >=80 B $score >=70 C $score >=60 D $score <60 F Call grade($score) function and output the table with the letter grade
49
Forms and User Input Any form element in an HTML page will automatically be available to your PHP scripts. Name: Age:
50
welcome.php Welcome ! You are years old. Browser validation is faster and reduces the server load. Consider server validation if the user input will be inserted into a database
51
$_GET Function Built-in $_GET function is used to collect values in a form with method="get". GET method Information is visible to everyone (it will be displayed in the browser's address bar) Has limits on the amount of information to send (max. 100 characters).
52
Example Name: Age: When the user clicks the "Submit" button, the URL sent to the server could look something like this: http://www.w3schools.com/welcome.php?fname=Peter&age=37 The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array): Welcome. You are years old!
53
When to use method="get"? When using method="get" in HTML forms, all variable names and values are displayed in the URL. Note: This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The get method is not suitable for large variable values; the value cannot exceed 100 characters.
54
$_POST Function Built-in $_POST function is used to collect values from a form sent with method="post". POST method Information sent from a form is invisible to others Has no limits on the amount of information to send
55
Example Name: Age: When the user clicks the "Submit" button, the URL will look like this: http://www.w3schools.com/welcome.php The "welcome.php" file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array): Welcome ! You are years old.
56
When to use method="post"? Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. The PHP $_REQUEST Function The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST function can be used to collect form data sent with both the GET and POST methods. Example Welcome ! You are years old.
57
Advanced features Server Side Includes (SSI) You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors: include() generates a warning, but the script will continue execution require() generates a fatal error, and the script will stop These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages. Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).
58
Example To implement templates on your website.
59
Examples Step 1: Universal header and footer in a single file Create a file called header.php. This file will have all of the header HTML code. You can use Aptana/Dreamweaver to create the header, but remember to remove the closing and tags. UCR Webmaster Support Group Page Title
60
Examples Step 2: Universal header and footer in a single file Next, create a file called footer.php. This file will have all of the footer HTML code. UC Riverside Department someuser@ucr.edu
61
Examples Step 3: Universal header and footer in a single file 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. <?php // header include(“header.php”); ?> Insert content here! <?php // footer include(“footer.php”); ?>
62
Examples Benefits: - Any changes to header or footer only require editing of a single file. This reduces the amount of work necessary for site maintenance and redesign. - Helps separate the content and design for easier maintenance. Page 1 Content Page 5 Content Page 3 Content Page 2 Content Page 4 Content Header Footer
63
File Handling fopen() function Returns 0 (false) if unable to open the specified file.
64
File open modes
65
Closing a File Check End-of-file if (feof($file)) echo "End of file"; Note: You cannot read from files opened in w, a, and x mode!
66
Reading a File Line by Line echo fgets($file); Reading a File Character by Character echo fgetc($file);
67
Examples To implement a simple page counter
68
Examples
69
Next, output the counter value using PHP. Copy this line after the main block of code. This page has been viewed times. That’s it! The result should look something similar to:
70
Examples You can change the text around the tags to your liking. visitors.
71
File Upload Create an Upload-File Form Filename: specifies which content- type (binary data). input should be processed as a file.
72
upload_file.php 0) { echo "Error: ". $_FILES["file"]["error"]. " "; } else { echo "Upload: ". $_FILES["file"]["name"]. " "; echo "Type: ". $_FILES["file"]["type"]. " "; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb "; echo "Stored in: ". $_FILES["file"]["tmp_name"]; } ?>
73
Exercise Write an HTML form and a PHP script that: Allow user to upload only JPG image files. Hint: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg. When a JPG is uploaded, display it in the browser.
74
Cookies A cookie is often used to identify a user. A small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
75
To Create a Cookie setcookie(name, value, expire, path, domain);.... Note: The setcookie() function must appear BEFORE the tag.
76
Retrieve a Cookie Value The PHP $_COOKIE variable is used to retrieve a cookie value "; else echo "Welcome guest! "; ?>
77
How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past.
78
Sessions A PHP session allows you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
79
Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the tag:
80
Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
81
The isset() function checks if the "views" variable has already been set
82
Destroying a Session The unset() function is used to free the specified session variable: Completely destroy the session by calling the session_destroy() function:
83
Additional Resources PHP Manual http://docs.php.net/http://docs.php.net/ PHP Tutorial http://academ.hvcc.edu/~kantopet/php/index.phphttp://academ.hvcc.edu/~kantopet/php/index.php PHP Coder http://www.phpide.de/http://www.phpide.de/ JEdit http://www.jedit.org/http://www.jedit.org/ PHP's creator offers his thoughts on the PHP phenomenon, what has shaped and motivated the language, and where the PHP movement is heading http://www.oracle.com/technology/pub/articles/php_experts/rasmus_php.html http://www.oracle.com/technology/pub/articles/php_experts/rasmus_php.html Hotscripts – A large number of PHP scripts can be found at: http://hotscripts.com/PHP/Scripts_and_Programs/index.html http://hotscripts.com/PHP/Scripts_and_Programs/index.html
84
Additional Information Some of the new functions added in version 5: Arrays: array_combine() - Creates an array by using one array for keys and another for its values array_combine() array_walk_recursive() - Apply a user function recursively to every member of an array array_walk_recursive() Date and Time Related: idate() - Format a local time/date as integer idate() date_sunset() - Time of sunset for a given day and location date_sunset() date_sunrise() - Time of sunrise for a given day and location date_sunrise() time_nanosleep() - Delay for a number of seconds and nano seconds time_nanosleep() Strings: str_split() - Convert a string to an array str_split() strpbrk() - Search a string for any of a set of characters strpbrk() substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters substr_compare() Other: php_check_syntax() - Check the syntax of the specified file php_check_syntax() php_strip_whitespace() - Return source with stripped comments and whitespace php_strip_whitespace()
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.