Upload
janasira1
View
217
Download
0
Embed Size (px)
Citation preview
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 1/16
2/12/2010
1
Chapter 6:Web Programming with PHP
Saminda Premaratne
PHP
• PHP is similar to JavaScript, only it’s a server-side language PHP code is embedded in HTML using tags when a page request arrives, the server recognizes PHP content via the file
extension (.php or .phtml)
the server executes the PHP code, substitutes output into the HTML page the resulting page is then downloaded to the client user never sees the PHP code, only the output in the page PHP is a loosely typed language.
• 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 server plug-ins exist for various servers now fully integrated to work with mySQL databases
• The acronym PHP means (in a slightly recursive definition) PHP: Hypertext Preprocessor
What do You Need?
• Server supports PHP
– You don't need to do anything special! *
– You don't need to compile anything or install any extra tools!
– Create some .phpfiles in your web directory - and the server willparse them for you.
* Slightly different rules apply when dealing with an SQL database (as will be explained whenwe get to that point).
• Most servers support PHP
– Download PHP for free here: http://www.php.net/downloads.php
– Download MySQLfor free here:http://www.mysql.com/downloads/index.html
– Download Apache for free here:http://httpd.apache.org/download.cgi
Test PHP and ApacheTest PHP and Apache•Test the Apache Server as
• Create php folder in
D:\SoftwareInstallation\ApacheGroup\Apache2\htdocsor where you have installed Apache
•Create first.php in htdocs\php folder(D:\SoftwareInstallation\ApacheGroup\Apache2\htdcs\php) with the following lines:
<?php
phpinfo();
?>
•Open the browser and type the following link
http://localhost:8088/php/first.php
the port number 8088 may be different in yourinstallation. You will be prompted the phpinformation on the browser.
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 2/16
2/12/2010
2
How it worksHow it works
PHP execution•PHP code can be embedded within a <?php...?> tag – output is displayed using print
6
<!-- hello.php -->
<html>
<head>
<title>Server-side Hello</title>
</head>
<body>
<table border=1 align="center">
<tr><td>
<?php print("Hello and welcome to <i>my</i> page!"); ?>
</table>
</body>
</html>
<!-- hello.php --><html>
<head>
<title>Server-side Hello</title>
</head>
<body>
<table border=1 align="center">
<tr><td>
Hello and welcome to <i>my</i> page!
</table>
</body>
</html>
the server executes theprint statement, substitutesoutput, downloads resultingpage
7 2010-2-12
Comments in PHP
•• Standard C, C++, and shell comment symbolsStandard C, C++, and shell comment symbols
// C++ and Java-style comment
# Shell-style comments
/* C-style comments
These can span multiple lines */
• Multiple statements on one line: A statement is the informal
word for an “expression” in compilers, terminated by ; ,e.g.
• Multiple “code islands” in the same source file, e.g.
<?php
// option 1
print "Hello, ";
print "world!";
// option 2
print "Hello, "; print "world!";
?>
<?php
print "Hello, "; // codeisland
?>
<?php
print "world!";
?>
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 3/16
2/12/2010
3
Variables• Variables in PHP are represented by a dollar sign followed by
the name of the variable. The variable name is case-sensitive.
• Variable names follow the same rules as other labels in PHP. Avalid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores,e.g.
Constantsmay be defined using the define( ) function, and retrieved by
its name or the constant( ) function
e.g.
White space
Any number of spaces, tabs and new lines are allowed between
statements and within function call, e.g.
<?php
echo "Something“,
"another thing“;
?>
has the same effect as :
<?php echo“Something”,”another thing”; ?>
Data Types
• PHP supports eight primitive types.
• Four scalar types:
• boolean
• integer
• float (floating-point number, aka 'double')
• string
• Two compound types:
• array
• object
• And finally two special types:
• resource
• NULL
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 4/16
2/12/2010
4
IntegersCan be defined in decimal , octal or hexadecimal( but not binary), e.g.
No Integer overflow. A large integer is automatically converted to float.,e.g.
$large_number = 2147483648;var_dump($large_number);// output: float(2147483648)
14 2010-2-12
Echo example
•• Notice how echo ‘Notice how echo ‘55xx55=$foo’ outputs $foo rather than replacing it with=$foo’ outputs $foo rather than replacing it with 2525
•• Strings in single quotes (‘ ‘) are not interpreted or evaluated by PHPStrings in single quotes (‘ ‘) are not interpreted or evaluated by PHP
•• This is true for both variables and character e scapeThis is true for both variables and character e scape--sequences (such as “sequences (such as “\\n” orn” or““\\\\”)”)
<?php
$foo = 25; // Numerical variable$bar = “Hello”; // String variable
echo $bar; // Outputs Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=“,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
Double Quoted String
expands variables and escape characters,e.g.
<?php
$x=“some_string”;
echo “this is $x”;
// outputs “this is some_string”
?>
Escape
characters
Basic PHP syntaxA PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed (almost) anywhere in an HTML document.
<html>
<!-- hello.php COMP519 -->
<head><title>Hello World</title></head>
<body>
<p>This is going to be ignored by the PHP interpreter.</p>
<?php echo ‘<p>While this is going to be parsed.</p>‘; ?>
<p>This will also be ignored by PHP.</p>
<?php print(‘<p>Hello and welcome to <i>my</i> page!</p>');
?>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
The server executes the print and echo statements, substitutes output.
print and echofor output
a semicolon (;)at the end of eachstatement
// for a single-line comment
/* and */ for a largecomment block.
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 5/16
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 6/16
2/12/2010
6
Conditionals: switch
Can select one of many sets of lines to execute<html><head></head>
<body>
<!–- switch-cond.php COMP519 -->
<?php
$x = rand(1,5); // random integer
echo “x = $x <br/><br/>”;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";break;
default:
echo "No number between 1 and 3";
break;
}
?>
</body>
</html>
switch (expression)
{
case label1:
code to be executed ifexpression = label1;
break;
case label2:
code to be executed ifexpression = label2;
break;
default:
code to be executedif expression is different
from both label1 and label2;
break;
}
Looping: while and do-whileCan loop depending on a condition
<html><head></head>
<body>
<?php
$i=1;
while($i <= 5)
{
echo "The number is $i <br />";
$i++;
}
?>
</body>
</html>
loops through a block of code if, andas long as, a specified condition istrue
<html><head></head>
<body>
<?php
$i=0;
do
{
$i++;
echo "The number is $i <br />";
}
while($i <= 10);
?>
</body>
</html>
loops through a block of code once,and then repeats the loop as longas a special condition is true (sowill always execute at least once)
Looping: for and foreachCan loop depending on a "counter"
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
loops through a block of code aspecified number of times
<?php
$a_array = array(1, 2, 3, 4);
foreach ($a_array as $value)
{
$value = $value * 2;
echo “$value <br/> \n”;
}
?>
loops through a block of code for eachelement in an array
<?php
$a_array=array("a","b","c");
foreach ($a_array as $key => $value)
{
echo $key." = ".$value."\n";
}
?>
User Defined FunctionsCan define a function using syntax such as the following:
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>
Can also define conditionalfunctions, functions within functions,and recursive functions.
<?php
function square($num)
{
return $num * $num;
}
echo square(4);
?>
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
echo $zero, $one, $two;?>
Can return a value of any type
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2));?>
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 7/16
2/12/2010
7
Variable ScopeThe scope of a variable is the context within which it is defined.
<?php
$a = 1; /* limited variable scope */
function Test()
{
echo $a;
/* reference to local scope variable */
}
Test();
?>
The scope is local within functions,and hence the value of $a isundefined in the “echo” statement.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
global
refers to itsglobalversion.
<?php
function Test()
{
static $a = 0;
echo $a;$a++;
}
Test1();
Test1();
Test1();
?>
static
does not loseits value.
Including FilesThe include() statement includes and evaluates the specified file.
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
*The scope of variables in “included” files depends on where the “include” file is added!
You can use the include_once, require, and require_once statements in similar ways.
<?php
function foo()
{
global $color;
include ('vars.php‘);
echo "A $color $fruit";
}
/* vars.php is in the scope of foo() so *
* $fruit is NOT available outside of this *
* scope. $color is because we declared it *
* as global. */
foo(); // A green apple
echo "A $color $fruit"; // A green
?>
• The header() function is used to send raw HTTP headers over the HTTP
protocol.
• Note: This function must be called before anything is written to the page!
• The following example will redirect the browser to the following URL:
http://www.w3schools.com/:
PHP Header() FunctionPHP Information
The phpinfo() function is used to output PHP information about the version installed on theserver, parameters selected when installed, etc.
<html><head></head>
<!– info.php COMP519
<body>
<?php
// Show all PHP information
phpinfo();
?>
<?php
// Show only the general informationphpinfo(INFO_GENERAL);
?>
</body>
</html>
INFO_GENERAL The configuration line,php.ini location,build date,Web Server,System and more
INFO_CREDITS PHP 4 creditsINFO_CONFIGURATION Local and master values
for php directives
INFO_MODULES Loaded modules
INFO_ENVIRONMENT Environment variableinformation
INFO_VARIABLES All predefined variablesfrom EGPCS
INFO_LICENSE PHP license information
INFO_ALL Shows all of the above (default)
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 8/16
2/12/2010
8
Server VariablesThe $_SERVER array variable is a reserved variable that contains all server information.
<html><head></head>
<body>
<?php
echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
?>
</body>
</html>
The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.
Another example: file uploading
30
the HTMLfile input element allows the user to browse for a file
<input type="file" name="ELEMENT_NAME">
once the user selects a file, can use a submit button to call a CGI or PHPprogram to process that file
<html>
<head>
<title>Simple File Uploader</title>
</head>
<body><form name="uploader" action="http://empirical.cs.creighton.edu/~davereed/upload.php"
enctype="multipart/form-data" method="post">Select file for uploading: <input type="file" name="userfile"><br /><br /><input type="submit" value="Upload File">
</form></body></html>
Robust file uploading
•<html><head><title>Simple File Uploader</title>
</head>
<body><form name="uploader" action="http://empirical.cs.creighton.edu/~davereed/upload.php"
enctype="multipart/form-data" method="post"><table><tr><td>Enter your user name:
<td><input type="text" name="userID" size=10 value=""><tr><td>Select file for uploading:
<td><input type="file" name="userfile"></table><input type="submit" value="Upload File">
</form></body></html>
31
could utilize other PHP features to make file uploading more robust
allow multiple students to submit same assignment each student specifies a user name, file is uploaded into a subdirectory
Robust file uploading• <?php
• $userID = $_POST['userID'];
• $BASEDIR = "/var/www/davereed/files/";
• $_FILES['userfile']['name'] = explode(' ', $_FILES['userfile']['name']);
• $_FILES['userfile']['name'] = implode('_', $_FILES['userfile']['name']);
• if (IsSet($userID)) {
• $BASEDIR = $BASEDIR.$userID."/";
• if (!file_exists($BASEDIR)) {
• mkdir($BASEDIR, 755);
• }
• }
• if (!file_exists($BASEDIR.$_FILES['userfile']['name'])) {
• move_uploaded_file($_FILES['userfile']['tmp_name'],
• $BASEDIR.$_FILES['userfile']['name']);
• print("File uploaded successfully");
• }
• else {
• print("File already exists - no upload performed.");
• }
• ?>
32
get the user ID from text box
replace ' ' with '_'in file name
if user ID is entered,extend path & create
directory if deosn'talready exist
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 9/16
2/12/2010
9
Getting Time and Date
date() and time () formats a time or a date.
<?php
//Prints something like: Monday
echo date("l");
//Like: Monday 15th of January 2003 05:51:38 AM
echo date("l jS \of F Y h:i:s A");
//Like: Monday the 15th
echo date("l \\t\h\e jS");
?>
date() returns a stringformatted according to thespecified format.
*Here is more on date/time formats: http://uk.php.net/manual/en/function.date.php
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secsecho 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
?>
time() returnscurrent Unixtimestamp
The PHP $_GET and $_POST variablesare used to retrieve information from
forms, like user input.
The most important thing to notice when dealing with HTMLforms and PHP is that any form element in an HTML page willautomatically be available to your PHP scripts.
Form example:
<html><body><form action="welcome.php" method="post“>
Name:<input type="text" name="name" />Age:<input type="text" name="age"/><input type="submit" />
</form></body></html>
The example HTML page above contains two input fields anda submit button. When the user fills in this form and click onthe submit button, the form data is sent to the"welcome.php" file.
The "welcome.php" file looks like this:
<html><body><form action="welcome.php" method="post“>
Welcome <?php echo $_POST["name"]; ?>.<br />You are <?php echo $_POST["age"]; ?> years old.
</form></body></html>
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 10/16
2/12/2010
10
• A sample output of the above script may be:
Welcome Imran.You are 28 years old.
The $_GET variable is used to collectvalues from a form with
method="get".
The $_GET variable is an array of variable names and valuessent by the HTTP GET method.
The $_GET variable is used to collect values from a form withmethod="get". Information sent from a form with the GETmethod is visible to everyone (it will be displayed in thebrowser's address bar) and it has limits on the amount of
information to send (max. 100 characters).
<form action="welcome.php" method="get“>Name:<input type="text" name="name" />Age:<input type="text" name="age"/><input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent could look something like this:
Welcome <?php echo $_GET["name"]; ?>.<br />You are <?phpecho $ _GET["age"]; ?> years old!
http://www.onestepsoltuions.biz/welcome.php?name=Peter&age=37
The "welcome.php" file can now use the $_GET variable to catch the form data (notice that thenames of the form fields will automatically be the ID keys in the $_GET array):
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 11/16
2/12/2010
11
Note: When using the $_GET variable all variablenames and values are displayed in the URL. So thismethod should not be used when sendingpasswords or other sensitive information!However, because the variables are displayed inthe URL, it is possible to bookmark the page. Thiscan be useful in some cases.
Note: The HTTP GET method is not suitable on
large variable values; the value cannot exceed 100characters.
• The PHP $_REQUEST variable contains thecontents of both $_GET, $_POST, and$_COOKIE.
• The PHP $_REQUEST variable can be used toget the result from form data sent with boththe GET and POST methods.
Welcome<?php echo$_REQUEST["name"]; ?>.<br />You are <?php echo$_ REQUEST["age"]; ?> years old!
Example
The $_POST variable is used to collectvalues from a form with
method="post".
• The $_POST variable is an array of variablenames and values sent by the HTTP POSTmethod.
• The $_POST variable is used to collect values
from a form with method="post".Information sent from a form with the POSTmethod is invisible to others and has nolimits on the amount of information to send.<form action="welcome.php" method="post">Enter yourname: <input type="text" name="name" />Enter yourage: <input type="text" name="age" /><input type="submit" /></form>
Example
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 12/16
2/12/2010
12
When the user clicks the "Submit" button, the URL will not contain any form data, and willlook something like this:
Welcome <?php echo $_POST["name"]; ?>.<br />You are <?php echo $_POST["age"]; ?> years old!
http://www.onestepsoltuions.biz/welcome.php
The "welcome.php" file can now use the $_POST variable to catch the form data (notice that thenames of the form fields will automatically be the ID keys in the $_POST array):
• Variables sent with HTTP POST are not
shown in the URL
• Variables have no length limit
• However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.
• The PHP $_REQUEST variable contains thecontents of both $_GET, $_POST, and$_COOKIE.
• The PHP $_REQUEST variable can be used to
get the result from form data sent with boththe GET and POST methods.
Welcome<?php echo$_REQUEST["name"]; ?>.<br />You are<?php echo$_ REQUEST["age"]; ?> years old!
Example
Maintaining State
• Because each HTTP connection is terminatedafter a single GET or POST request, we say thatHTTP is a stateless protocol.
• Additionally, our programs normally handle asingle GET or POST request and thenterminate.
• It is desirable, however, to maintain session
information for each user.
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 13/16
2/12/2010
13
User Sessions
• There are a number of reasons why we maywant to maintain information for the durationof a user session:
– To allow users to login and then view a number of pages;
– To allow multi-screen forms;
– To "carry around" data, such as a "shopping cart";
– To develop a profile of each user (what they haveviewed before, what they are interested in etc)
The State Problem
• There are a number of solutions to the
problem of maintaining state information
across PHP program invocations:
– Including forms in the generated pages, with data
placed in fields (often hidden)
– Placing links to the script in generated pages, with
the data placed as a parameter
– Cookies
Cookies
• The cookie standard was developed by
Netscape, and has since been adopted by IE
and other browsers.
• It allows pages to include directives to beincluded in their headers to store small
amounts of data on the client machine.
• Programs that are part of the same site can
then later read the data back again.
What is a Cookie
• A small piece of information that is passesbetween ad HTTP client and an HTTP server.
• This information can be used to add state tothe stateless HTTP protocol.
• Sharing state information via cookies allowsthe server to uniquely identify each client andmaintain user-specific settings
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 14/16
2/12/2010
14
Cookies (cont).
• A cookie is basically a name-value pair.
• All cookies are stored within a single file on
the client machine and thus there is no
security risk.
• Cookies have an expiration date or expire
when the user quits the browser.• You can also specify in what circumstances the
cookie will be sent to the server.
Using Cookies
• Normally, we don't create cookies for all of thevalues we might need later.
• Instead we create a single cookie thatidentifies the user, and then store theinformation on disk on the server.
• When the user invokes a program we check
for the existence of a cookie, and if we findone we load up the session or profileinformation for that user.
Write the Advantages of Cookies Advantages of Cookies
• Simplest way to store state information on the client
because this information need only be stored once.
• Cookies do not require parsing of the requested URL
or the HTML document. Information can be
extracted from the client.
• Provide a simple method of maintaining state and
session with very low overhead.
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 15/16
2/12/2010
15
Disadvantages of Cookies
• They are not supported by all browsers.
• Possobility that a user might manually disablecookies support and in turn, disable a Websites mechanism for state and sessionmanagement.
• it stored as plain-text in a specific directory,
everyone can view and modify them. Personalinformation is exposed.
A PHP session variable is used to store informationabout, or change settings for a user session. Sessionvariables hold information about one single user,
and are available to all pages in one application.
When you are working with an application, you open it, do somechanges and then you close it. This is much like a Session. Thecomputer knows who you are. It knows when you start theapplication and when you end. But on the internet there is oneproblem: the web server does not know who you are and what youdo because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store userinformation on the server for later use (i.e. username, shoppingitems, etc). However, session information is temporary and will bedeleted after theuser hasleft the website. If you need a permanentstorage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor andstore variables based on this UID. The UID is ei ther stored in acookie or is propagated in theURL.
• Before you can store user information in yourPHP session, you must first start up the session.
• Note: The session_start() function must appearBEFORE the <html> tag:
<?php session_start(); ?><html><body></body></html>
The code above will register the user's session with the server, allow you to start saving userinformation, and assign a UID for that user's session.
7/31/2019 Chapter 6 PHP
http://slidepdf.com/reader/full/chapter-6-php 16/16
2/12/2010
16
• The correct way to store and retrieve
session variables is to use the PHP
$_SESSION variable:<?php
session_start();// store session data$_SESSION['views']=1;
?><html><body>
<?php//retrievesession dataecho "Pageviews=". $_SESSION['views'];?>
</body></html>
Pageviews=1
In the example below, we create a simple page-views counter. The isset() functionchecks if the "views" variable has already been set. If "views" has been set, we canincrement our counter. If "views" doesn't exist, we create a "views" variable, and set itto 1:
<?phpsession_start();if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];?>
<?phpunset($_SESSION['views']);
?>
If you wish to delete some session data, you can use the unset() or thesession_destroy() function.
The unset() function is used to free the specified session variable:
<?phpsession_destroy();
?>
You can also completely destroy the session by calling the session_destroy() function:
Note: session_destroy() will reset your session and you will lose all your stored sessiondata.