What We Will Cover
Elucidations
Homework Questions?
Homework Discussion Questions
- How many people have worked with cookies before? What did you use them for and why did you think they were an appropriate tool to accomplish what you needed to do?
- What practical uses can you envision for cookies beyond those discussed in the textbook?
- When passing data from one page to another, what are the advantages and disadvantages of cookies compared to appending data to a URL?
Question About the Course
- Would you prefer to:
- Spend another hour in class each week and not post discussion topics
- Read the text and post discussions but not spend another hour in class?
^ top
12.1: Getting Started With PHP
Objectives
At the end of the lesson the student will be able to:
- Discuss how PHP pages are processed
- Create and run a simple PHP script
- Describe the development process for PHP
- Install the components needed to run PHP on a computer
|
^ top
12.1.1: Introduction to PHP
- PHP is a programming language that can run on a Web server
- PHP stands for "PHP Hypertext Processor"
- Running a programming language on a Web server provides several advantages:
- You can dynamically generate HTML and client-side scripts
- Processing is done in a known environment, unlike Javascript
- You can isolate common page elements in one file for inclusion in multiple pages
- You can connect to databases to take advantage of their power
- Many server-side programming languages exist, of which PHP is one of the most popular
Brief History of PHP
- 1994 - Rasmus Lerdorf created PHP
- Used it to keep track of who was looking at his online resume
- 1995 - Other people started using PHP
- 1997 - About 50,000 users of PHP world-wide with many contributors
- 2000 - PHP 4 released
- 2002 - Most popular scripting language on the Web
- 2005 - PHP 5 released
What Can PHP Do?
- Perform calculations
- Dynamically generate the HTML (and JavaScript) returned to the browser
- Create different content for different users
- Automatically send email
- Validate the data a user enters into forms
- Connect to databases to store and retrieve data
- Access and change files on the server
- Create server-side redirects
- Create sessions and track users across multiple Web pages of a site
- Generate GIF and PNG images dynamically
- Control online games
^ top
12.1.2: How PHP Web Applications Work
- Web applications are a set of Web pages generated in response to user requests
- Users typically interact with the Web application using a browser
- The browser contacts a Web server to request a Web page or other data
- When the browser requests a Web page that uses PHP several steps occur
- Many of these steps are invisible to the user
- User enters query (URL) into a browser (client)
- Browser connects to server and sends a request for a PHP file
- Web server receives the request, finds the file and reads it
- PHP scripting engine executes the PHP statements, usually returning HTML to the Web server
- Web server sends the results back to the client
- Results get sent over the Internet
- Browser receives results and displays them to the user
^ top
12.1.3: Creating PHP Documents
^ top
12.1.4: PHP Development Process
- Developing PHP-enhanced HTML documents consists of three steps
- Writing the PHP (and HTML) code
- Copying the coded files to the server
- Accessing the file on the server using a browser
- This process is repeated many times during development
Writing Code
- You can use any text editor to create PHP code, just like you can for HTML
- For instance, we could enter the code in TextPad
- Some people like to use Web development tools to create HTML and PHP
- However, I do not recommend them when learning PHP because:
- Some tools write PHP code for you, which does not help you learn
- These are complex tools that themselves are difficult to learn
- Learning to use the tool can distract you from your goal of learning PHP
- I do recommend using development tools if you code professionally because:
- You can place components on the Web page more easily
- You can improve your productivity
Copying Files to the Server
- If you have access to a Web server running PHP, you can copy your file to the server using FTP
- For instance, you can upload to WebHawks with CoreFTP
- To access your pages on WebHawks use:
http://webhawks.org/~yourusername/
Viewing the File
- You view a PHP-enhanced Web page using a browser
- In the browser's address bar, enter the Web address of the file
- Note: do NOT use the "Open File" command in your browser
- Remember that all PHP pages must be processed by a Web server
- Otherwise, the PHP code is not processed
^ top
12.1.5: Components Needed for PHP Development
- To develop PHP documents you need access to a Web server and a PHP engine
- While you ultimately want to publish your work on the Web, it is more convenient to develop your code on your own computer
- It turns out that installing a Web server and PHP on your own computer is simple and free
- For instructions, see How To Install PHP and MySQL
Using localhost
^ top
12.1.6: Summary
- PHP is a programming language that can run on a Web server
- It was first developed by Rasmus Lerdorf in 1994
- PHP files are stored on a web server
- When the user requests a PHP file, the web server asks PHP to answer the request
- The web server knows when to do this based on the file extension
- Thus, every PHP file must end in
.php
- You must copy all PHP files to a location accessible by the web server
- To view the file, you use a browser to access the web server
- To make development easier, you can install the Web server and PHP engine on your own computer
- To access files using the Web server on your computer, you use the name
localhost
Check Yourself
- What is the difference between dynamic HTML and dynamic Web pages?
- What is a Web application?
- What does the Web server do with a page with a suffix of .php?
- How do you code a PHP tag?
- How do you view a PHP-enhanced Web page?
- What is wrong with using the File Open command for viewing a PHP-enhanced Web page?
- What software components do you need for developing PHP on your own computer?
- What is meant by the term "localhost"?
^ top
Activity 12.1
In this exercise, we install PHP on the computers in the classroom.
Specifications
- Install PHP by following the instructions in How To Install PHP and MySQL.
- If you have difficulty, ask another classmate or the instructor for help.
- Please keep track of any problems you have so we can discuss them.
^ top
12.2: Creating PHP Scripts
Learner Outcomes
At the end of the lesson the student will be able to:
- Code a PHP script tag
- Discuss PHP statements and whitespace rules
- Create comments in PHP
- Describe how to avoid common PHP syntax problems
|
^ top
12.2.1: Working with the PHP Tag
- Programmers commonly embed PHP scripts within HTML tags
- Only the output from PHP statements gets displayed in the page
- However, you can create HTML tags within the PHP as well
- The following script demonstrates both techniques
<html>
<head>
<title>Generating HTML from PHP</title>
</head>
<body>
<h1>Generating HTML from PHP</h1>
<?php
print "<p>Generating HTML in PHP statements</p>";
print "</body></html>";
?>
- We can save this file using a name like
embedded.php
- The file name must follow the rules for a PHP file and end with
.php
- Otherwise, the Web server will not send the file to the scripting engine
- If the above were saved as
embedded.html, we would see very different output
- To save the file with localhost access on our classroom machines, we save to the directory:
C:\Program Files\xampp\htdocs
^ top
12.2.2: Understanding Statements and Whitespace Rules
PHP Ignores Most Extra White Space
- Whitespace is any sequence of non-printing characters like:
- Blank spaces
- Blank lines
- Tabs
- Like HTML, PHP ignores most occurrences of extra white space
- This means that you can add extra spaces in your code to make it easier to read
- Typically, you start statements on a new line
- If the statement get too long, then you wrap it to another line
- There are coding standards describing how to use whitespace to format your PHP code
- For more information, see: How To Document and Organize Your PHP Code
^ top
12.2.3: Comments in PHP
- You use comments to describe your code to people
- Comments are ignored when the script runs
- Using comments does not measurably slow down your code
- You should use comments in two cases:
- To describe the purpose of the script
- To describe particularly tricky lines of code
- Comments can start with two forward slash marks (
//)
- These last from the slashes to the end of the line
- For example:
<?php
// This is a comment
?>
- You can add comments like these after a code statement, like:
<?php
print "A simple script"; //Output a line
?>
- Alternatively, you can create single-line comments using a pound sign (
#):
<?php
print "A simple script"; #Output a line
?>
- Another easy way to make comments is:
/* ... */
- This style allows multi-line comments, such as:
<?php
/*
This is a
multiline comment
*/
?>
- Also, this style allows all or part of a line to be commented:
<?php
/* here comes the code */ print "A simple script";
?>
^ top
12.2.4: Importance of Proper Syntax
Avoiding Common Syntax Problems
- End most PHP statements with a semicolon (
;)
- Realize that PHP ignores extra whitespace
- Use quotation marks, parenthesis and brackets in pairs
^ top
12.2.5: Summary
Check Yourself
- What is the syntax of a PHP tag?
- How do you separate statements in PHP?
- What is meant by the term "whitespace"?
- How do you code a multi-line comment?
- What are the three way of coding a single-line comment?
- What is wrong with the following PHP statement?
<?php
print "The message to print;
?>
^ top
Exercise 12.2
In this exercise we look at how to create a PHP script file and view it in a web browser. Be prepared to answer the questions after the exercise.
Specifications
- Save the following file using the name
embedded.php in a directory that the Web server can access.
If you installed XAMPP on Windows XP, the root directory of the Web server is: C:\Program Files\xampp\htdocs
<html>
<head>
<title>Generating HTML from PHP</title>
</head>
<body>
<h1>Generating HTML from PHP</h1>
<?php
print "<p>Generating HTML in PHP statements</p>";
print "</body></html>";
?>
- Load the file using the URL for the localhost server. For instance, if you save in the root directory of the server, you would use the URL:
http://localhost/embedded.php
- View the source of the Web page.
Q1: When you view the source of the page, do you see any PHP code?
- Try adding PHP comments to your
embedded.php file.
Q2: Where in the file are you able to add PHP comments without the comments appearing in the source of the Web page?
- Create an error in the PHP script by removing one of the double-quote marks (
")
Q3: What error did PHP report??
- Now load the file using the File Open menu of the browser.
Q4: Does the output appear different than previously?
- View the source of the browser page.
Q5: When you view the source of embedded.html, do you see the PHP code?
Q6: How do you explain the difference?
^ top
12.3: Working with Variables and Data Types
Objectives
At the end of the lesson the student will be able to:
- Store and access data in PHP variables
- Recognize literal data values
- Display variable values in a Web document
|
^ top
12.3.1: Introduction to PHP Variables
- Recall that a variable is the name of a location in a computer's memory
- In this location you can store a single number, text string or logical value
- Values stored in a variable can change (vary) as the program runs
Creating Variables
- When you create a variable, you tell the computer to reserve memory space
- To create a variable in PHP, you make up a name and start using the variable
- However, you have to follow certain rules when you make up a variable name
- The syntax for creating a variable:
$variableName
- Where variableName is the name you make up
- For example:
$userName
Naming a Variable
- A variable name is a dollar sign (
$) followed by letters, numbers, or underscore characters
- However, PHP has some limitations on variable names
- The first character of a variable name must always be a dollar sign (
$)
- The second character must be a letter or an underscore (
_ )
- Any of the following characters can be a:
- Letter
- Digit
- Underscore (
_ )
- Note that variable names cannot contain any periods or spaces
- Also note that variable names cannot be a reserved keyword
- In addition, variable names are cAsE sEnSiTiVe!
$id, $ID, $iD and $Id are all valid, but different, identifiers
Check Yourself
Which of the following are valid identifiers?
$myHello2
$2myHello
$My_HeLlO
$my hello
$a_very_long_variable_name_that_is_hard_to_read
$hel-lo
Programming Style: Variable Naming Conventions
- Professional programmers follow naming conventions when creating names
- Conventions are not required by PHP but make code easier to read
- One convention is to start variable names with a lowercase letter (after the dollar sign)
- Another is to use uppercase letters or underbars ('_') as word separators
$myVar
$my_var
- Another good practice is to choose names that describe the value that the variable stores
- For example:
$counter is more descriptive than $c
^ top
12.3.2: Assigning a Value to a Variable
^ top
12.3.3: Writing a Variable Value to a Web Document
A More Complicated Example
^ top
12.3.4: PHP Data Types
Check Yourself
What is the data type for each of the following?
- false
- 0.33
- -128
- "$3.95"
PHP is Weakly Typed
^ top
12.3.5: Summary
Check Yourself
- How do you store data in a program?
- What are the four scalar data types supported by PHP?
- What code do you use to declare a variable named
weekDay and assign it a value of "Friday"?
^ top
Activity 12.3
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
12.4: Arithmetic Using Operators and Functions
Objectives
At the end of the lesson the student will be able to:
- Work with arithmetic operators to construct expressions
- Make use of PHP functions
|
^ top
12.4.1: Using Arithmetic Operators
Example of Arithmetic
Explanation of Code
- The relevant part is the PHP code
- First we create two variables and assign them values:
$apples = 12;
$oranges = 14;
- The next line adds the two variables and assigns the value to a new variable:
$totalFruit = $apples + $oranges;
- Then the
print statement displays the value of the $total_fruit variable:
print "The total number of fruit is $totalFruit";
- Showing that using PHP you can add apples and oranges
^ top
12.4.2: Mathematical Functions
- There are many common mathematical operations that are not provided by operators
- Instead, PHP provides the Mathematical Functions library
- Functions include:
abs(), pow(), max(), min(), rand(), round(), sqrt(), log(), and trig functions
- The library also includes common math constants such as:
M_PI (approximately 3.141592653)
M_E (base of natural logarithms, approximately 2.71828182)
- If you need to handle big numbers you can use the BCMath Arbitrary Precision Mathematics Functions
Arguments
- Most mathematical functions require you to send them one or more arguments
- An argument is an input value that functions use in processing
- Usually mathematical functions return a value based on the arguments
Examples
$value = pow(2, 3); // value gets int 8
print($value);
$num = -2.0;
$value = abs($num); // value gets float 2.0
print($value);
Other Predefined PHP Functions
- PHP offers many libraries of predefined functions
- For a complete list see the Function Reference
- One of the main attractions of PHP is the large number of predefined functions you can make use of in your scripts
^ top
12.4.3: Writing Complex Expressions
- Can use many operators and functions in the same expression:
$x = 1 + 2 * 3;
- What is the value of
$x after this statement?
- The value of
$x might be either 9 or 7
- The correct answer depends on the order in which PHP applies the arithmetic operators
- The computer follows certain rules when evaluating an expression
Precedence, Associativity and Other Arithmetic Rules
- Arithmetic operators are processed in a precedence order like in algebra:
- Functions
- Parenthesis: ( )
- Multiplication, division, modulus: *, /, %
- Addition, subtraction: +, -
- Operators with the same precedence are evaluated from left to right
- You can use parenthesis to group expressions
- You can have parenthesis within parenthesis
- Innermost parenthesis evaluated first
- However, you cannot use parenthesis or dots to indicate multiplication
- Instead, you must always use the
* operator
- Note that using parenthesis to specify and clarify operator precedence is a good idea
Examples of Expressions
| Algebra Expression |
PHP Expression |
| 2 (10 + 5) |
2 * (10 + 5) |
1
12.3 + 3 · 7.3 |
1 / (12.2 + 3 * 7.3) |
10 - 7
3.3 + 9 · 1.6 |
(10 - 7) / (3.3 + 9 * 1.6) |
| 2 · 42 |
2 * 4 * 4 |
^ top
12.4.4: Summary
- You can perform arithmetic on numeric values:
$num = $num + 2;
- PHP supports all the standard math operations:
$a = 2;
$b = 4;
print $a + $b // Addition: Sum of $a and $b
print $a - $b // Subtraction: Difference of $a and $b
print $a * $b // Multiplication: Product of $a and $b
print $a / $b // Division: Quotient of $a and $b
print $a % $b // Modulus: Remainder of $a divided by $b
- When you want to perform more complicated math operations, you use mathematical functions:
$value = pow($a, $b);
print($value);
- You can use many operators and functions in the same expression:
$average = ($a + $b) / 2;
^ top
Wrap Up
Due Next: Final Project Report and Presentation (12/11/06)
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: November 25 2006 @15:13:10
|