Sie sind auf Seite 1von 16

2/12/2010

PHP

Chapter 6: Web Programming with PHP

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 PHP is similar to JavaScript, only its 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. The acronym PHP means (in a slightly recursive definition) PHP: Hypertext Preprocessor

Saminda Premaratne

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 .php files in your web directory - and the server will parse them for you.
* Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point).

Test PHP and Apache


Test the Apache Server as Create php folder in
D:\SoftwareInstallation\ApacheGroup\Apache2\htdocs or where you have installed Apache

Most servers support PHP Download PHP for free here: http://www.php.net/downloads.php Download MySQL for free here: http://www.mysql.com/downloads/index.html Download Apache for free here: http://httpd.apache.org/download.cgi

Create first.php in htdocs\php folder (D:\SoftwareInstallation\ApacheGroup\Apache2\htdo cs\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 your installation. You will be prompted the php information on the browser.

2/12/2010

How it works

PHP execution
PHP code can be embedded within a <?php...?> tag
output is displayed using
print
<!-- 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 the print statement, substitutes output, downloads resulting page

Comments in PHP
Standard 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.
<?php // option 1 print "Hello, "; print "world!"; // option 2 print "Hello, "; print "world!"; ?>

Multiple code islands in the same source file, e.g.


<?php print "Hello, "; island ?> <?php print "world!"; ?> // code

2010-2-12

2/12/2010

Variables
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-

Constants
may be defined using the define( ) function, and retrieved by its name or the constant( ) function

sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores, e.g.

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,

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

"another thing; ?>

has the same effect as :


<?php echoSomething,another thing; ?>

2/12/2010

Integers
Can be defined in decimal , octal or hexadecimal ( but not binary), e.g.

Echo example
<?php $foo = 25; $bar = Hello; echo echo echo echo echo ?> $bar; $foo,$bar; 5x5=,$foo; 5x5=$foo; 5x5=$foo; // Numerical variable // String variable // // // // // Outputs Outputs Outputs Outputs Outputs Hello 25Hello 5x5=25 5x5=25 5x5=$foo

No Integer overflow. A large integer is automatically converted to float., e.g.


$large_number = 2147483648; var_dump($large_number); // output: float(2147483648)

Notice how echo 5x5=$foo outputs $foo rather than replacing it with 25 5 Strings in single quotes ( ) are not interpreted or evaluated by PHP This is true for both variables and character escape-sequences (such as \n or escape\ \\)

14

2010-2-12

Double Quoted String


expands variables and escape characters,e.g.
<?php $x=some_string; echo this is $x; // outputs this is some_string ?>

Basic PHP syntax


A 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

print and echo for output a semicolon (;) at the end of each statement

// for a single-line comment /* and */ for a large comment block.

Escape characters

/* This is a comment block */ ?> </body> </html>

The server executes the print and echo statements, substitutes output.

2/12/2010

Scalars
All variables in PHP start with a $ sign symbol. A variable's type is determined by the context in which that variable is used (i.e. there is no strong-typing in PHP).
<html><head></head> <!-- scalars.php COMP519 --> <body> <p> <?php $foo = true; if ($foo) echo "It is TRUE! <br /> \n"; $txt='1234'; echo "$txt <br /> \n"; $a = 1234; echo "$a <br /> \n"; $a = -123; echo "$a <br /> \n"; $a = 1.234; echo "$a <br /> \n"; $a = 1.2e3; echo "$a <br /> \n"; $a = 7E-10; echo "$a <br /> \n"; echo 'Arnold once said: "I\'ll be back"', "<br /> \n"; $beer = 'Heineken'; echo "$beer's taste is great <br /> \n"; $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD; echo $str; ?> </p> </body> </html>

Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys.
<?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?>

array() = creates arrays key = either an integer or a string. value = any PHP type. if no key, the maximum of the integer indices + 1. if an existing key, its value will be overwritten. can set values in an array unset() removes a key/value pair array_values() makes reindexing effect (indexing numerically) *Find more on arrays

Four scalar types: boolean true or false integer, float, floating point numbers string single quoted double quoted

<?php array(5 => 43, 32, 56, "b" => 12); array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?>

<?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // the same as $arr[13] = 56; $arr["x"] = 42; // adds a new element unset($arr[5]); // removes the element unset($arr); // deletes the whole array $a = array(1 => 'one', 2 => 'two', 3 => 'three'); unset($a[2]); $b = array_values($a); ?>

Operators
Arithmetic Operators: +, -, *,/ , %, ++, - Assignment Operators: =, +=, -=, *=, /=, %=
Example x+=y x-=y x*=y x/=y x%=y Is the same as x=x+y x=x-y x=x*y x=x/y x=x%y

Conditionals: if else
Can execute a set of code depending on a condition
<html><head></head> <!-- if-cond.php COMP519 --> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend! <br/>"; else echo "Have a nice day! <br/>"; $x=10; if ($x==10) { echo "Hello<br />"; echo "Good morning<br />"; } ?> </body> </html>

if (condition) code to be executed if condition is true; else code to be executed if condition is false;

Comparison Operators: ==, !=, >, <, >=, <= Logical Operators: &&, ||, ! String Operators: . and .= (for string concatenation)
$a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!";

date() is a built-in PHP function that can be called with many different parameters to return the date (and/or local time) in various formats In this case we get a three letter string for the day of the week.

2/12/2010

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>

Looping: while and do-while


Can loop depending on a condition
<html><head></head> <body> <html><head></head> <body> <?php $i=0; do { $i++; echo "The number is $i <br />"; } while($i <= 10); ?> </body> </html> <?php $i=1; while($i <= 5) { echo "The number is $i <br />"; $i++; } ?> </body> </html>

switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; break; }

loops through a block of code if, and as long as, a specified condition is true

loops through a block of code once, and then repeats the loop as long as a special condition is true (so will always execute at least once)

Looping: for and foreach


Can loop depending on a "counter"
<?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> <?php $a_array = array(1, 2, 3, 4); foreach ($a_array as $value) { $value = $value * 2; echo $value <br/> \n; } ?> <?php $a_array=array("a","b","c"); foreach ($a_array as $key => $value) { echo $key." = ".$value."\n"; } ?>

User Defined Functions


Can 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 conditional functions, functions within functions, and recursive functions.

Can return a value of any type


<?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();

loops through a block of code a specified number of times

echo $zero, $one, $two;


?>

loops through a block of code for each element in an array

<?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; }

takes_array(array(1,2));
?>

2/12/2010

Variable Scope
The 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(); ?> <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?>

Including Files
The include() statement includes and evaluates the specified file.
vars.php <?php $color = 'green'; $fruit = 'apple'; ?> test.php <?php echo "A $color $fruit"; // A <?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. */ // A green apple // A green

The scope is local within functions, and hence the value of $a is undefined in the echo statement.

global refers to its global version.

<?php function Test() { static $a = 0; echo $a; $a++; } Test1(); Test1(); Test1(); ?>

include 'vars.php';

static does not lose its value.

echo "A $color $fruit"; // A green apple ?> foo(); echo "A $color $fruit"; ?>

*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 Header() Function


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 Information
The phpinfo() function is used to output PHP information about the version installed on the server, parameters selected when installed, etc.
<html><head></head> <! info.php COMP519 <body> <?php // Show all PHP information phpinfo(); ?> <?php // Show only the general information phpinfo(INFO_GENERAL); ?> </body> </html> INFO_GENERAL The configuration line, php.ini location, build date, Web Server, System and more PHP 4 credits Local and master values for php directives Loaded modules Environment variable information All predefined variables from EGPCS PHP license information

INFO_CREDITS INFO_CONFIGURATION INFO_MODULES INFO_ENVIRONMENT INFO_VARIABLES

>lmth/< >ydob/< ...... >ydob< >lmth< >? ;)"/moc.sloohcs3w.www//:ptth :noitacoL"(redaeh resworb tcerideR// php?<

INFO_LICENSE INFO_ALL

Shows all of the above (default)

2/12/2010

Server Variables
The $_SERVER array variable is a reserved variable that contains all server information.

Another example: file uploading


the HTML file input element allows the user to browse for a file

<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>

<input type="file" name="ELEMENT_NAME">

once the user selects a file, can use a submit button to call a CGI or PHP program 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>

The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.

30

Robust file uploading


could utilize other PHP features to make file uploading more robust

Robust file uploading


<?php $userID = $_POST['userID']; $BASEDIR = "/var/www/davereed/files/";

allow multiple students to submit same assignment each student specifies a user name, file is uploaded into a subdirectory

get the user ID from text box replace ' ' with '_' in file name

$_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."); } ?>

<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>

if user ID is entered, extend path & create directory if deosn't already exist

31

32

2/12/2010

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 string formatted according to the specified format.

<?php $nextWeek = time() + (7 * 24 * 60 * 60); // 7 days; 24 hours; 60 mins; 60secs echo 'Now: '. date('Y-m-d') ."\n"; echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n"; ?>

time() returns current Unix timestamp

The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

*Here is more on date/time formats: http://uk.php.net/manual/en/function.date.php

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically 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 and a submit button. When the user fills in this form and click on the 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>

2/12/2010

A sample output of the above script may be:

Welcome Imran. You are 28 years old.

The $_GET variable is used to collect values from a form with method="get".

When the user clicks the "Submit" button, the URL sent could look something like this:

The $_GET variable is an array of variable names and values sent by the HTTP GET method. The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters).

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 the names of the form fields will automatically be the ID keys in the $_GET array):

Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! <form action="welcome.php" method="get> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>

10

2/12/2010

Note: When using the $_GET variable all variable names and values are displayed in the URL. So 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 HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_ REQUEST["age"]; ?> years old!

The $_POST variable is used to collect values from a form with method="post".

The $_POST variable is an array of variable names and values sent by the HTTP POST method. The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST Example method is invisible to others and has no <form action="welcome.php" method="post"> limits on the amount of information to send. Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" /> <input type="submit" /> </form>

11

2/12/2010

When the user clicks the "Submit" button, the URL will not contain any form data, and will look something like this: http://www.onestepsoltuions.biz/welcome.php

The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array):

Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old!

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.

Maintaining State
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_ REQUEST["age"]; ?> years old!

Because each HTTP connection is terminated after a single GET or POST request, we say that HTTP is a stateless protocol. Additionally, our programs normally handle a single GET or POST request and then terminate. It is desirable, however, to maintain session information for each user.

12

2/12/2010

User Sessions
There are a number of reasons why we may want to maintain information for the duration of 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 have viewed 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 be included 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 passes between ad HTTP client and an HTTP server. This information can be used to add state to the stateless HTTP protocol. Sharing state information via cookies allows the server to uniquely identify each client and maintain user-specific settings

13

2/12/2010

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 the values we might need later. Instead we create a single cookie that identifies the user, and then store the information on disk on the server. When the user invokes a program we check for the existence of a cookie, and if we find one we load up the session or profile information 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.

14

2/12/2010

Disadvantages of Cookies
They are not supported by all browsers. Possobility that a user might manually disable cookies support and in turn, disable a Web sites mechanism for state and session management. it stored as plain-text in a specific directory, everyone can view and modify them. Personal information is exposed.

A PHP session variable is used to store information about, or change settings for a user session. Session variables 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 some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing 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.

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 <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 user information, and assign a UID for that user's session.

15

2/12/2010

Pageviews=1

The correct way to store and retrieve session variables is to use the PHP <?php session_start(); $_SESSION variable: // store session data
$_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html>

In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:

<?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>

If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable:

<?php unset($_SESSION['views']); ?>

You can also completely destroy the session by calling the session_destroy() function:

<?php session_destroy(); ?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

16

Das könnte Ihnen auch gefallen