cpan542-lec8

advertisement
Server Side Programming with PHP CPAN 542
Lecture 8: Introduction to PHP
PHP, known as the Personal Home Page Tools, is a server-side script
language that is embedded inside an HTML document. The language itself
looks like some other existing languages like C and Perl with support for a
wide range of database connectivity.
PHP documents must have the extension (. php) and you need a PHP aware
server to run PHP script. HAL server at Humber is configured to process
PHP documents. You can also install Apache server on your local machine
and configure it to run PHP. See ReadMe 1st section if you want to install
Apache on your local machine.
Generally speaking PHP instructions can be embedded in an HTML
document in many ways:

Between <?php and ?> tags (the preferred one), for example:
<?php echo ("Hello World"); ?>

Between <? and ?> for example:
<? echo ("Hello World"); ?>

Between <script> and </script> tags, for example:
<script language="php">
echo ("Hello Wolrd");
</script>
Where the echo statement is used to output data.
Statements in PHP are terminated with a semicolon, and in the case of the
last statement, the closing tag ?> is considered as the ending of a statement.
Example:
<?php
echo("first string");
echo("second string");
echo("third string") ?>
1
The White space characters like the new line, tab, and space are ignored by
the PHP engine.
In order to use comments in PHP, you can use either C/C++ style or UNIX
style comments. For example:
<?php
// this is one line comment
/*
here we have a block of
comments
*/
# this is Unix style comment
?>
If you have some static content, you can mix PHP and HTML tags as shown
in the following example:
<?php
if (i==0)
?>
<p> false</p>
<?php
else
?>
<p> true</p>
Generally speaking, PHP supports four primitive data types: Boolean,
integer, floating-point number and string, plus two compound types: array
and object.
Variables in PHP are not typed and are automatically declared the first time
they are assigned values. Variables can be explicitly typecast , and any
variable must start with ($) For example:
$ name=”my Name”;
$age=21;
Here name will be declared as a string variable and age as integer variable.
2
One of the important things to know about strings is that double-quoted
strings are subject to variable substitution and escape sequence, whereas
single-quoted strings are not.
For example :
$name=”Robert”;
echo “\nHello $name”;
Here the output will be: newline, then the string Hello Robert
Whereas if you use single-quoted string
$name=”Robert”;
echo ‘\nHello $name’;
The output will be \nHello $name.
Following are some of the escape sequences supported by PHP:
\n
new line.
\r
carriage return.
\t
tab.
\\
back slash.
\$
dollar sign.
The period operator( .) is used to concatenate strings. For example:
$name=”Robert”; echo "hello". $name;
Constants can be defined using the define standard function. For example to
define a constant called TAX:
define('TAX',0.15);
Operators and control structure in PHP are very similar to those used in C
language (For more details, refer to Chapter 1 of the textbook). One of
these operators in the error suppression operator @. You can place this
operator in front of any statement to suppress error messages.
3
PHP provides many internal functions plus user-defined functions. You can
pass any number of arguments to a function, either by value or by reference.
For example, assume we have a function called multiply defined as follow:
function multiply( $x)
{
$x=$x*2;
return $x;
}
We can pass argument to this function by value which means a copy of the
original variable will be passed as follows:
$val=10;
print multiply($val);
print $val;
this will output :
20
10
Whereas if we pass an argument by reference, it means the original
value of the variable will be changed permanently, as follows:
$val=10;
print multiply(&$val);
print $val;
this will output :
20
20
Variables defined inside functions are local to those functions, whereas
variables defined in the PHP main script are global in scope. To access a
global variable from inside a function, prefix it with the keyword global. PHP
also supports static variables and build-in super global variables.
When PHP handles HTTP requests, it provides built-in super global variables
as an associative arrays that contain all the passed data to the page.
Following is a complete list of the built-in super global variables:


$_GLOBALS: An array of all global variables.
$_GET: An array of variables passed to the script from an HTML form
using get method.
4







$_POST: An array of variables passed to the script from an HTML form
using post method.
$_SERVER: An array contains a reference to every variable which is
currently available within the global scope of the script.
$_COOKIE: An array containing all the cookies variables.
$_FILES: An array contains variables provided to the script via HTTP
post file uploads.
$_ENV:An array of all environment variables.
$_REQUEST:An array of all user input variables.
$_SESSION: An array contains variables which are currently registered
to a script's session.
For example, assume we have an HTML form with a text field called name.
Then if this form is submitted using post method, then it will be available in
the PHP file through:
$_POST[“name”]
if this form is submitted using get method, then it will be available in the PHP
file through:
$_GET[“name”]
Note:
If register_globals is turned on in the configuration file php.ini, then PHP will
automatically creates global variables for all data it receives. For the example
above, a global variable called $name will be made available for the PHP
processing file. In our examples we will use the associative arrays syntax,
because register_globals is usually turned off on HAL server.
One of the important features of PHP is its ability to include files. The file to be
included must start in HTML mode which means if you have PHP code then it
must be enclosed within valid PHP tags. The included file has access to the
variables declared in the including file directly.
When working with date and time, you can use any of the following date and
time formats:
Character
Description
a
"am" or "pm"
A
"AM" or "PM"
d
day of the month (01-31).
D
three letters day of the week (Sun–Fri).
5
F
full month name (January-December).
g
hour, 12-hour format without leading zeros (1-12).
G
hour, 24-hour format without leading zeros (0-23).
h
hour, 12-hour format (01-12).
H
hour, 24-hour format (00-23).
i
minutes (00-59).
j
day of the month without leading zeros (1-31).
l
full day of the week name (Sunday-Saturday).
L
boolean for whether it is a leap year (0 or 1) .
m
month number (01-12).
M
three letter month name (Jan-Dec).
n
month number without leading zeros (1-12)
s
seconds (00-59).
S
English ordinal suffix (st, nd, rd, th).
t
number of days in the given month; (28-31).
T
Time zone setting.
y
year (2 digits).
Y
year (4 digits).
w
day of the week number (0-6)
z
day of the year (0-365).
Examples
Example 1: info.php
In this example, we will print some information about PHP using the phpinfo
function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First PHP Document</title>
</head>
<body>
<?php
echo ("<h1 align='center' style='background-color: #6666cc;'>Welcome
to PHP. It is really fun!</h1>\n"
);
echo("<p style='background-color: #00cccc;'><i>Below is some useful
information</i></p><br
6
/>\n");
phpinfo();
?>
</body>
</html>
Example 2: including.php
In this example, the file inform.inc will be included in the file including.php.
Notice how inform.inc has access to the variables declared in including.php
before the including call.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled</title>
</head>
<body>
<?php
$name="John Smith";
$today= (date ("D F Y h:i:s A"));
include("inform.inc") ?>
</body>
</html>
and inform.inc is:
<?php
echo $name;
echo $today;
?>
the output will be
John Smith Wed November 2001 10:23:55 PM
Example 3: env.php
In this example, we will output the date and time and some of the server side
environment variables:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
7
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Information about the server</title>
</head>
<body>
<h1 align="center">Some Server Side information using PHP</h1>
<?php
echo ("Today date is :<b>");
echo (date ("l, dS of F Y h:i:s A"));
echo (" </b> <br />the server name is
:<b>".$_SERVER['SERVER_NAME']." </b><br/>");
echo ("the server protocol name is
:<b>".$_SERVER['SERVER_PROTOCOL']." </b><br/>");
echo ("the server port number is :<b>".$_SERVER['SERVER_PORT']."
</b><br \>");
echo ("the client browser name is
:<b>".$_SERVER['HTTP_USER_AGENT']." </b><br/>");
echo ("the client browser IP address is
:<b>".$_SERVER['REMOTE_ADDR']." </b><br/>")
?>
</body>
</html>
Example4:form.html
In this example we will use basic arithmetic operators. The user has to fill a
form called form.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Form </title>
</head>
<body>
<?php
?>
<a></a>
<form method="post"
action="http://hal.humberc.on.ca/~abdullah/cpan542/operators.php">
First value <input type="text" name="var1" />
<br/>
Second value <input type="text" name="var2" />
<br/>
<input type="submit"/>
<input type="reset"/>
8
</form>
</body>
</html>
Below is the PHP file operators.php that will process form.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Operators Examples </title>
</head>
<body>
<?php
$x=$_POST["var1"];
$y=$_POST["var2"];
@ settype($x,"double");
@ settype($y,"double");
echo ' x= '.$x."<br/>";
echo ' y= '.$y."<br/>";
echo ' $x +$y= ';
echo $x+$y."<br/>" ;
echo ' $x -$y= ';
echo $x-$y."<br/>" ;
echo ' $x/$y= ';
echo $x/$y."<br/>" ;
echo ' $x*$y= ';
echo $x*$y."<br/>" ;
?>
</body>
</html>
Example5:functions.php
This example shows some of the many standard PHP functions:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Functions </title>
9
</head>
<body>
<?php
echo "Here are some of the standard functions in PHP <br/>";
echo "Today date is ".date("M,d Y")."<br/>";
echo "The current time is ".date("H:i:s")."<br/>";
echo "Generating a random number between 0 and 100 result is :
".rand(0,100);
echo "<br/> Rounding the number 500.5499 result is ".round(500.5499);
echo "<br/> The length of the string cpan542 is :".strlen("cpan542");
echo "<br/> Converting cpan542 to uppercase letters
:".strtoupper("cpan542");
echo "<br/> replaces pan with eng
:".substr_replace("cpan542","eng",1,3);
?>
</body>
</html>
Example 6: login.html
This is a simple example of a login validation, where the user must fill the a
form called: login.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Page </title>
</head>
<body>
<?php
?>
<a></a>
<form method="post"
action="http://hal.humberc.on.ca/~abdullah/cpan542/login.php">
User ID <input type="text" name="uID" />
<br/>
User password <input type="password" name="uPW" />
<br/>
<input type="submit"/>
<input type="reset"/>
</form>
</body>
</html>
10
The login is then validated by a PHP document called login.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login example </h1>
<?php
$user1="john";
$password1="123";
$user2="rob";
$password2="456";
if( ( strcmp($_POST['uID'],$user1)==0 && strcmp($_POST['uPW'],
$password1)==0 ) ||
(strcmp($_POST['uID'],$user2)==0 && strcmp($_POST['uPW'],
$password2)==0))
echo "login successful";
else
{
echo "login unsuccessful, <a
href='http://hal.humberc.on.ca/~abdullah/cpan542/login.html'>try again
</a>";
}
?>
</body>
</html>
?>
</body>
</html>
Example 7: userFunctions.php
In this example, we will use functions to generate HTML form elements,
dynamically using arrays to hold the elements and loop through these arrays
using for statement:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>User Functions </title>
</head>
11
<body>
<?php
function multiply( $x)
{
$x=$x*2;
return $x;
$myVar=50;
echo "passing myVar by value to multiply yields ".multiply($myVar);
echo "<br/> myVar after calling multiply is ".$myVar;
echo "<br/>passing myVar by reference to multiply yields
".multiply(&$myVar);
echo "<br/> myVar after calling multiply is ".$myVar;
?>
</body>
</html>
12
Download