cset3300-module

advertisement
PHP Basics
CSET3300
Architecture of Web Applications
Web Browser
Browser
Browser
Browser
Browser
Browser
Browser
Web Server
(Apache, IIS)
Middleware
(PHP, Asp, ColdFusion)
Relational Database
MySQL, MS-SQL,
Oracle, etc.
2
PHP
• What is PHP?
– PHP (Hypertext Preprocessor),
– Server-side script language for web development
– Support operating systems (Linux, many Unix variants (including HP-UX, Solaris
and OpenBSD), Microsoft Windows, Mac OS X, RISC OS)
• History:
–
–
–
–
developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
originally designed as a tool for tracking visitors at Lerdorf's Web site
within 2 years, widely used in conjunction with the Apache server
developed into full-featured, scripting language for server-side
programming
– free, open-source
3
PHP Scripts
• PHP is server-side
– PHP code is embedded in HTML using tags
– When a page request arrives, the server recognizes PHP content via the
file extension (.php , .php3, or .phtml)
– The server executes the PHP code, substitutes output into the HTML
– The resulting page is then downloaded to the client
– User never sees the PHP code, only the output in the page
• When it comes to develop your own PHP projects, remember that you can
only use PHP to send information (HTML and such) to the Web browser.
• You can’t do anything else within the Web browser until another request
from the server has been made (a form has been submitted or a link has
been clicked).
• PHP is cross-platform, meaning that it can be used on machines running Unix,
Windows, Macintosh, and other operating systems.
4
Why PHP?
• PHP’s advantage over basic HTML is that the latter is a limited system
allowing for no flexibility or responsiveness.
– Visitors accessing HTML pages see simple pages with no level of
customization or dynamic behavior.
• With PHP, you can create exciting and original pages based on whatever
factors you want to consider (for example, the time of day or the user’s
operating system).
• PHP can also interact with databases and files, handle email, and do many
other things that HTML can’t.
5
Writing PHP Scripts
 A sample PHP code:
<html>
<head>
<title>PHP Test Page</title>
</head>
<body>
<?php
echo “Hello, World
?>
!!!”;
</body>
</html>
 Note these important characteristics:



PHP code and HTML tags are both present
Files containing PHP code must use the php extension
The code above should named as <filename>.php and placed in a
web-accessible directory on the class server.
6
Testing PHP Scripts
 Create “public_html” directory on et791
 Place your .php file in the directory
 In a web browser type

http://et791.ni.utoledo.edu/~<utadID>/<filename.php>
7
PHP Basics
 PHP code must be placed within HTML code if
the output is to be displayed by your browser
 Note these important characteristics:




PHP code is enclosed between beginning and ending tags
PHP statements end with a semicolon character (;)
PHP statements can be broken across multiple lines, as long as
tokens are not broken
Whitespace is ignored
 Use the "view source" function of your browser to see
what has been generated by the code.
8
PHP Basics: Displaying Output
 We could also use the print() statement (actually, it is a
PHP language construct) to display output.
 You may use either print() or echo() as they are
functionally equivalent.
 Note that you can use print() and echo() with or
without the parentheses. Most programmers will omit
the parentheses. You can also safely omit the
quotation marks when only printing variable values.
For example, the following are all equivalent:
print ("$name");
print "$name";
print $name;
9
PHP Basics: Variables
 Variable identifiers are marked with a
preceding dollar sign ($).
 You
could display "Hello, World!" using PHP
variables as follows:
<?php
$message = "Hello, World Again!";
echo $message;
?>
10
PHP Variable Identifiers
 The following guidelines apply to your selection of variable identifiers:
 All PHP variable identifiers (names) must begin with the dollar sign ($),
following the dollar sign, the variable name must begin with a letter of the
alphabet (A-Z, a-z) ) or an underscore character ( _ )
 Variable names cannot begin with a number, but after the dollar sign and
initial character (letter or underscore) may contain any combination of
letters, underscores and numbers
 Variable names are case sensitive, so $name is NOT the same as $Name
 Avoid variables with similar names
 Keep variable names reasonably short and meaningful
 Spaces may NOT be used in variable names
 Valid PHP variable names include the following examples:
$LastName
$last_name
$session_22
$COST
$FN
$page_title_num_1
11
PHP Variable Declaration
 PHP does not require explicit variable declaration wherein you specify
the data type for the variable.
 You simply use the variable as needed. All the variable data types look
identical but may be handled differently.
 The following code shows how to assign string, integer, and floatingpoint (double) values to variables:
$a
$b
$c
$d
=
=
=
=
"this is a string";
4;
4.837;
"2" ;
 Basically, PHP determines the variable data type based on the value you
assign.
12
PHP Basics: Arithmetic Operators
 PHP arithmetic operators are what you would
expect. Some of the basic ones are illustrated
below:
<?php
$greeting = "Hello ";
$num = 3 + 2;
$num++;
echo "$greeting $num people!";
?>
Output :
Hello 6 people!
13
PHP Basics: Strings
 Just as in Perl, a string surrounded with
double quotes causes variables inside it to be
interpolated, but a string surrounded with
single quotes does not.
<?php
$name = 'Susannah';
$greeting_1 = "Hello, $name!";
$greeting_2 = 'Hello, $name!';
echo "$greeting_1\n";
echo "$greeting_2\n";
?>
Output:
Hello, Susannah! Hello, $name!
14
PHP Basics: “\” Character
 Note that the \n in the string inserts a new line into the output stream,
just as in Perl or in C.
 However, this only works in double-quoted strings.
 Other special "escaped characters" include the tab \t and carriage
return \r, dollar \$.
 Here is another interesting use of the backslash character.
<?php
$name = 'Susannah';
$greeting = "Hello, \"$name\"!";
echo "$greeting\n";
?>
 How would you include a backslash character in the displayed output?
15
PHP Basics: Comments
 PHP supports C, C++ and Unix shell style comments.
 For example, the following code segment illustrates all of the possibile
comment delimiters:
<?php
echo 'This is a test'; // This is a one-line C++ style comment
/* This is a multi line C style comment that continues on more than
one line */
echo 'This is another test';
echo 'Still another test'; # This is a one-line shell style comment
?>
 Use the "view source" function of your browser to see what has been
generated by this "commented" code.
16
PHP Basics: More on Comments
 Note these important characteristics:




C++ style and Shell style comments can be on the same line as a PHP
statement or on a line by themselves
C style comments can be a single line or multiple line
in "real" code, consistancy is better than trying to use every
comment style available
Nesting C style comments can cause problems because the C style
comments end with the first encountered */ delimiter. You should be
careful not to nest C style comments, a common temptation when
commenting large blocks. For example:
<?php
/*
echo 'This is a test'; /* This comment will cause a problem */
*/
?>
17
PHP Arrays
 An array is a special data type that can store multiple values using the
same variable identifier.


The commonly used term for each value in an array is an element.
Each individual array element can be accessed by the array index, which can
be a number or a string.
 If the array index is a string, the array is known as an associative array.
 You set off array indices (regular or associative) with square brackets ([
and ]):
$fruit[0] = 'banana';
$fruit[1] = 'papaya';
$favorites['animal'] = 'turtle';
$favorites['monster'] = 'cookie';
 By default, index values start at zero, and arrays are assumed to be zerobased.

In other words, if an array has five elements, the first element will be
referenced as $my_array[0] and the last value will be referenced as
$my_array[4].
18
PHP Arrays (ctd)
 If you assign something to an array but leave the index blank, PHP
assigns the object onto the end of the array.
 The statements about $fruit, above, produce the same result as:
$fruit[] = 'banana';
$fruit[] = 'papaya';
 You can have multidimensional arrays, too:
$people['David']['shirt'] = 'blue';
$people['David']['car'] = 'minivan';
$people['Adam']['shirt'] = 'white';
$people['Adam']['car'] = 'sedan';
19
PHP Arrays (ctd)
 A shortcut for creating arrays is the array()
function:
$fruit = array('banana','papaya');
$favorites = array('animal' => 'turtle', 'monster' => 'cookie);
$people = array ('David' => array('shirt' => 'blue', 'car' => 'minivan'),
'Adam' => array('shirt' => 'white', 'car' => 'sedan'));
 The built-in function count() tells you how
many elements are in an array:
$fruit = array('banana','papaya');
echo count($fruit);
Output:
2
20
PHP Built-in Functions
 phpinfo(): A function that displays important
information about our installation of PHP.
<?php
phpinfo();
?>
 Use the "view source" function of your browser to see
what has been generated by this code.
 With respect to its statements and functions, PHP is
not case sensitive. The examples below illustrate this
fact, showing equivalent forms for phpinfo():
phpInfo();
PHPinfo();
pHpInFo();
21
PHP Date & Time Functions
 The basic PHP date and time functions let you
format timestamps for use in database queries
or simply for displaying the date and time in
the browser window.
 PHP includes the following date and time
functions:
 date(format)
- Returns the current server time,
formatted according to a given set of parameters.

The next slide contains valid date() formats:
 time()
- Returns the current server time, measured
in seconds since January 1, 1970.
22
PHP Date Function: Example-1
<?php
echo date("Y/m/d");
echo "<br />";
echo date("Y.m.d");
echo "<br />";
echo date("Y-m-d");
?>
Output:
2006/07/11
2006.07.11
2006-07-11
a
Prints "am" or "pm"
A
Prints "AM" or "PM".
h
Hour in 12-hour format (01 to 12)
H
Hour in 24-hour format (00 to 23)
g
Hour in 12-hour format without a leading zero (1 to 12)
G
Hour in 24-hour format without a leading zero (0 to 23)
i
Minutes (00 to 59)
s
Seconds (00 to 59)
d
Day of the month in two digits (01 to 31)
D
Day of the week in text (Mon to Sun)
l
Day of the week in long text (Monday to Sunday)
F
Month in long text (January to December)
m
Month in two digits (1 to 12)
Y
Year in four digits (2005)
y
Year in two digits (05)
S
English ordinal suffix (th, nd, st)
23
PHP Date Function: Example-2
The following page uses the PHP date function to determine and
display the current server time and date:
<?php
echo "<span style='font:10pt arial'>Today is”.
date('lFjY').”</span>";
echo "<br/>";
echo "<span style='font:10pt arial'>The current time is:”.
date('g:i:s a').”</span>";
?>
Output:
Today is Wednesday, September 5, 2007
The current time is: 10:20:13 am
24
PHP Date Function: Example-3
String concatenation is done with the dot (.) character.
<?php
$todaysdate = date("m") . "-" . date("d") . "-" .date("Y");
echo $todaysdate;
?>
Output:
02-4-2010
25
PHP Mail Function
 The PHP mail() function is used to send emails
from inside a script.
 Syntax:
 mail(to,subject,message,headers,parameters)
Parameter
Description
To
Required. Specifies the receiver / receivers of the email
Subject
Required. Specifies the subject of the email. Note: This parameter
cannot contain any newline characters
Message
Required. Defines the message to be sent. Each line should be
separated with a LF (\n). Lines should not exceed 70 characters
Headers
Optional. Specifies additional headers, like From, Cc, and Bcc. The
additional headers should be separated with a CRLF (\r\n)
Parameters
Optional. Specifies an additional parameter to the sendmail program
26
PHP Mail Function: Example
 The simplest way to send an email with PHP is to send a text email.
 In the example below we first declare the variables ($to, $subject,
$message, $from, $headers), then we use the variables in the mail()
function to send an e-mail:
<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent!";
?>
27
Download