Académique Documents
Professionnel Documents
Culture Documents
Dep. of Electrical and Computer Engineering Faculty of Sciences and Technology University of Coimbra
1. What is PHP? .................................................................................................................. 2 2. Basics of PHP .................................................................................................................. 3 2.1 First Example ........................................................................................................... 3 2.2 Variables ................................................................................................................. 4 2.3 Comments ............................................................................................................... 4 2.4 Arithmetic Operators ................................................................................................ 5 2.5 Assignment Operators .............................................................................................. 5 2.6 Comparison Operators .............................................................................................. 6 2.7 Logical Operators ..................................................................................................... 6 3. Flow Control and Loops ................................................................................................... 6 3.1 Conditional Statements ............................................................................................. 6 3.2 Loops ...................................................................................................................... 8 4. Functions in PHP ............................................................................................................10 4.1 Information about PHP Function phpinfo() .............................................................10 4.2 Function header() ...................................................................................................11 4.3 Function date() .......................................................................................................12 4.4 Accessing Files ........................................................................................................12 5. Forms ............................................................................................................................15 6. Creating functions ..........................................................................................................15 6.1 Inclusion of other scripts inside of a script ................................................................16 7. Cookies .........................................................................................................................17 7.1 Creating a Cookie Function setcookie() ..................................................................17 7.2 Reading a Cookie Function isset() .........................................................................17 References .........................................................................................................................18 Checklist ............................................................................................................................18
Lab Work
MiEEC, DEEC-FCTUC
Databases
1. What is PHP?
PHP is a general-purpose scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document. PHP can be deployed on most web servers and as a standalone interpreter, on almost every operating system and platform free of charge. A competitor to Microsoft's Active Server Pages (ASP) server-side script engine and similar languages, PHP is currently installed on more than 20 million websites and 1 million web servers [1]. The acronym PHP stands for PHP: Hypertext Preprocessor. However, PHP originally stood for Personal Home Page. It was originally created by Rasmus Lerdorf in 1995. The main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification [2]. PHP is free software released under the PHP License. PHP is especially suited to server-side web development where PHP generally runs on a web server. Any PHP code in a requested file is executed by the PHP runtime, usually to create dynamic web page content or dynamic images used on web sites or elsewhere. PHP can be deployed on most web servers, many operating systems and platforms, and can be used with many relational database management systems (RDBMS). It is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their own use [2]. PHP primarily acts as a filter, taking input from a file or stream containing text and/or PHP instructions and outputs another stream of data; most commonly the output will be HTML. Since PHP 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine, giving improved performance over its interpreter predecessor. Originally designed to create dynamic web pages, PHP now focuses mainly on server-side scripting, and it is similar to other server-side scripting languages that provide dynamic content from a web server to a client, such as Microsoft's Asp.net, Sun Microsystems' JavaServer Pages, and mod_perl. The LAMP architecture has become popular in the web industry as a way of deploying web applications. PHP is commonly used as the P in this bundle alongside Linux, Apache and MySQL, although the P may also refer to Python or Perl or some combination of the three. WAMP packages (Windows/ Apache/ MySQL
Lab Work
Page 2/18
MiEEC, DEEC-FCTUC
Databases
/ PHP) and MAMP packages (Mac OS X / Apache / MySQL / PHP) are also available. As of April 2007, over 20 million Internet domains had web services hosted on servers with PHP installed and mod_php was recorded as the most popular Apache HTTP Server module. PHP is used as the server-side programming language on 75% of all web servers. Web content management systems written in PHP include MediaWiki, Joomla, eZ Publish, WordPress, Drupal and Moodle. All websites created using these tools are written in PHP, including the user-facing portion of Wikipedia, Facebook, and Digg.
2. Basics of PHP
Some examples are presented throughout this section and the following sections to introduce PHP. Use your student account to perform the proposed activities, i.e. edit and test these examples through a Web browser in your own webpage located in a URL like: http://alunos.deec.uc.pt/~a<student_number>...
Activity 1. Edit and test this first example (file: helloworld.php). Any block of PHP instructions embedded into the HTML file is delimited by tags <?php and ?> and can be placed anywhere inside the HTML file. Each line of PHP code must be terminated with ;. The most basic instructions to generate text in the HTML document are echo and print. In the example above, the former was used to print the message Hello World in the browser.
Lab Work
Page 3/18
MiEEC, DEEC-FCTUC
Databases
2.2 Variables
Every variable in PHP starts with character $. Variables may contain strings, numbers or tables. In the example below, the string Hello World is assigned to a variable named $txt.
1 2 3 4 5 6 7 8
<html> <body> <?php $txt="Hello World"; echo $txt; ?> </body> </html>
The character . can be used to concatenate two or more variables. In the example below, the message Hello World 1234 is printed in the browser.
1 2 3 4 5 6 7 8 9
<html> <body> <?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2 ; ?> </body> </html>
2.3 Comments
As in C++, the sequence // represents a single comment line and a multi-line block of comments is started with /* and ended with */. An example is presented below.
1 2 3 4 5 6 7 8 9 10 11 12
<html> <body> <?php // This is a comment /* This is a multi-line block of comments */ ?> </body> </html>
Lab Work
Page 4/18
MiEEC, DEEC-FCTUC
Databases
+ * /
x=2 x+2 x=2 5-x x=4 x*5 15/5 5/2 5%2 10%8 10%2 x=5 x++ x=5 x--
++ --
Increment Decrement
= += -= *= /= %=
Activity 3. Copy the file helloworld.php to operators.php and expand the code in the latter file to test the operands above. Use echo statements to show the operands result.
Lab Work
Page 5/18
MiEEC, DEEC-FCTUC
Databases
&& || !
x=6; y=3 (x < 10 && y > 1) x=6; y=3 (x==5 || y==5) x=6; y=3 !(x==y)
3.1.1 If Statement
The if statement has the following syntax:
1 2 3 4
if <condition> <block to be executed if condition is true> else <block to be executed if condition is false>
Lab Work
Page 6/18
MiEEC, DEEC-FCTUC
Databases
In the example below, the message Have a nice weekend will be presented if today is Friday and Have a nice day otherwise.
1 2 3 4 5 6 7 8 9 10 11
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html>
As in C/C++, if a conditional block has multiple statements, curly brackets are used to delimit them (see the example below).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<html> <body> <?php date_default_timezone_set('Europe/Lisbon'); $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!<br />"; echo "See you next week."; } else { echo "Have a nice day!<br />"; echo "See you tomorrow."; } ?> </body> </html>
switch <expression> { case <value1>: <block1> break; case <value2>: <block2> break; default: <default_block> break; }
The statement tests sequentially the enumerated cases until the value mentioned in a case statement matches the expression value. Then, the respective block is executed. The break statement is used to avoid executing automatically the
Lab Work
Page 7/18
MiEEC, DEEC-FCTUC
Databases
code block in next case. The default statement defines a block that is executed whenever none of the cases applies. An example is presented below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<html> <body> <?php $x=2; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "It is not a number between 1 and 3"; } ?> </body> </html>
Activity 5. Edit and test this example (file: whatnumber.php). Activity 6. Write the script today.php to print in the Web browser what weekday is today.
3.2 Loops
Loops are often required to repeat the execution of a sequence of statements. In PHP, loops can be programmed using the following statements: while executes a block while a given condition is true; dowhile executes a block once and repeat it while a given condition is true; for executes a block a given number of times; foreach executes a block for each element of a table.
The example below contains a loop that is repeated while a variable is less or equal than 5. The variable is incremented on each iteration.
1 2 3 4 5 6
Lab Work
Page 8/18
MiEEC, DEEC-FCTUC
Databases
7 8 9 10 11 12
echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html>
The example below contains a loop that is executed once and repeated while a variable is less than 5. The variable is incremented on each iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13
<html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html>
It has three parameters: the first one is used to set the loop counter initial value; the second one is the logical condition that must evaluate to true before each iteration, otherwise the loop ends; the third one is an arithmetic operation with the loop counter (e.g. increment counter). The example below displays 5 times the message Hello World. On each iteration, it also displays the counter value.
1 2 3 4 5 6 7
<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World! "; echo $i . "<br />";
Lab Work
Page 9/18
MiEEC, DEEC-FCTUC
Databases
8 9 10 11
This loop searches an array (or table). On each iteration, current entry is assigned to a variable and a pointer to the array is automatically set to point to next entry. The example below displays the contents of a simple array.
1 2 3 4 5 6 7 8 9 10 11
<html> <body> <?php $a=array("one", "two", "three"); foreach ($a as $value) { echo "Current element: " . $value . "<br />"; } ?> </body> </html>
4. Functions in PHP
In this section, some functions supported by PHP will be presented. Please refer to [3] for a complete list of functions and more detailed information.
<html> <body> <?php // General information only phpinfo(INFO_GENERAL); // All the information
Lab Work
Page 10/18
MiEEC, DEEC-FCTUC
Databases
7 8 9 10
Table 1. Options available in function phpinfo(). Option Description General information about PHP server PHP credits
<html> <body> <?php echo "URL: " . $_SERVER["HTTP_REFERER"] . "<br />"; echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />"; echo "IP address: " . $_SERVER["REMOTE_ADDR"]; ?> </body> </html>
Lab Work
Page 11/18
MiEEC, DEEC-FCTUC
Databases
<?php // Redirects the browser header("Location: http://www.uc.pt"); ?> <html> <body> <?php echo "Main body"; ?> </body> </html>
date(<date_format>[,int timestamp])
The first parameter is a string that allows specifying the display format; Table 2 (next page) presents the available options. The second one is optional and can be used to display a date different from current date. The example below calls twice function date().
1 2 3 4 5 6 7 8 9
<html> <body> <?php // e.g. Thursday 2nd June 2011, 5:49:45 PM $d = date("l jS F Y, g:i:s A"); echo "Today is " . $d . "."; ?> </body> </html>
Activity 14. Edit and test this example (file: date.php). Try different formats.
Lab Work
Page 12/18
MiEEC, DEEC-FCTUC
Databases
Table 2. Format options in function date(). Option Description am or pm AM or PM Swatch Internet time (000-999) Day of the month with a leading zero (01-31) Three characters that represent the day of week (Mon-Sun) The full name of the month (January-December) The hour in 12-hour format without a leading zero (1-12) The hour in 24-hour format without a leading zero (0-23) The hour in 12-hour format with a leading zero (01-12) The hour in 24-hour format with a leading zero (00-23) The minutes with a leading zero (00-59) 1 if the date is in daylight saving time, 0 otherwise Day of the month without a leading zero (1-31) The full name of the day (Monday-Sunday) 1 if the year is a leap year, 0 otherwise The month as number, with a leading zero (01-12) Three characters that represent the name of the month (Jan-Dec) The month as a number, without a leading zero (1-12) The difference to Greenwich time (GMT) in hours An RFC 822 formatted date (e.g. Tue, 2 Jun. 2011 17:23:35 +0400) The seconds with a leading zero (00-59) The English ordinal suffix for the day of the month (st, nd, rd or th) The number of days in the given month (28-31) The local time zone (e.g. GMT) The number of seconds since the Unix Epoch (Jan. 1 1970, 00:00:00, GMT) The day of week as a number (0-6, 0=Sunday) ISO-8601 week number of year, weeks starting on Monday The year as a 4-digit number (e.g. 2009) The year as a 2-digit number (e.g. 09) The day of the year as a number (0-366)
a A B d D F g G h H i I j l L m M n O r s S t T U w W Y y z
The function fclose() is used to close a file which was previously open with fopen().
1
fclose(<pointer>);
Lab Work
Page 13/18
MiEEC, DEEC-FCTUC
Databases
Table 3. Mode options in function fopen(). Mode Description Read only. The file pointer is set to the beginning of the file. Read/Write. The file pointer is set to the beginning of the file. Write only. Either clears the file if the file exists or creates a new file. Read/Write. Either clears the file if the file exists or creates a new file. Append. The file pointer is set to the end of the file if the file exists or creates a new file. Read/Append. The file pointer is set to the end of the file if the file exists or creates a new file. Create and open for writing only. If the file already exists, the fopen() call will return an error, otherwise creates it. Create and open for read/write. If the file already exists, the fopen() call will return an error, otherwise creates it.
r r+ w w+ a a+ x x+
feof(<pointer>);
Functions fgetc() and fwrite() can be used to, respectively, read a single character from a file or write a single character to a file. Both functions advance the file pointer. The file should have been open in the appropriate mode.
1
fgetc(<pointer>);
fwrite(<pointer>, <character>);
In the example below, a file is open in read mode, it is read and the number of characters read is displayed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<html> <body> <?php $name = "file.txt"; echo "Contents of the file '" . $name . "':<br /><br />"; $f = fopen($name, "r"); if (!$f) exit("ERROR: Cannot open file."); $c=0; $s = ""; while (!feof($f)) { $s = $s . fgetc($f); $c++; } echo $s; fclose($f); echo "<br /><br />" . $c . " characters was(were) read."; ?> </body> </html>
Lab Work
Page 14/18
MiEEC, DEEC-FCTUC
Databases
5. Forms
HTML allows defining forms to read data from keyboard. It is important to know how data can be automatically passed to a PHP script. The example below shows a HTML file with two text boxes to read data from keyboard.
1 2 3 4 5 6 7 8 9 10 11
<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> </body> </html>
When the user clicks in the submit button, the PHP script welcome.php is executed. It is presented below an example of a script that processes data inserted in the previous form.
1 2 3 4 5 6
<html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
Variables $_POST["name"] and $_POST["age"] are automatically defined by PHP. Table $_POST contains every data sent through POST method of HTML forms. Activity 16. Edit and test this example of a form (files: form.html and welcome.php).
6. Creating functions
It is possible to create new functions in PHP. This feature makes scripts more modular and makes easier reusing PHP code. A function may accept parameters and return a result with
1
return <result>; A function can only return one result. If a complex result needs to be
returned, an array can be returned. Parameters of a function are listed as an argument list, e.g.:
Lab Work
Page 15/18
MiEEC, DEEC-FCTUC
Databases
The function is called through its name and listing the parameters, e.g.:
1
The example below defines the function computeVolume() which accepts three parameters and computes a volume.
1 2 3 4 5 6 7
<?php function computeVolume($x, $y, $z) { $vol = $x * $y * $z; return $vol; } ?>
<html> <head> <!-- Redirects the browser after 3s --> <meta HTTP-EQUIV="refresh" content="5 url=volume.html"> <body> <?php require("computeVolume.php"); echo "The volume is equal to " . computeVolume($_POST["length"], $_POST["width"], $_POST["height"]) . " m3."; ?> </br /> </br /> </br /> You will be redirected to the initial page in 3s... </body> </html>
<html> <head> <title> Volume Computation </title> <body> <h1> Volume Computation </h1> <form action="callComputeVolume.php" method="POST"> Length (m): <input type="text" name="length" /> Width (m): <input type="text" name="width" /> Height (m): <input type="text" name="height" /> Page 16/18 MiEEC, DEEC-FCTUC
Lab Work
Databases
14 15 16 17
Activity
17. Edit and test this example (files: callComputeVolume.php and volume.html).
computeVolume.php,
7. Cookies
A cookie is used to identify a user or some information about the user (e.g. preferences). A cookie is a small file which the browser stores in the users computer. Whenever the same computer sends a request of a web page, the browser sends to the remote HTML server all the cookies stored in the local computer that are related with that server. It is possible to create and access cookies in PHP.
The example below creates a cookie named username which expires in 1 minute.
1 2 3 4 5 6 7 8
<?php setcookie("username", $nome, time()+60); ?> <html> <body> <p> A cookie was created in this page! It will be active for 1 minute. </p> </body> </html>
<html> <body> <?php if ( isset($_COOKIE["username"]) ) echo "Welcome " . $_COOKIE["username "] . "!<br />"; else echo "You are not registered in our system.<br />"; ?>
Lab Work
Page 17/18
MiEEC, DEEC-FCTUC
Databases
9 10
</body> </html>
Activity 18. Create a script that counts the number of visits to the page based on a cookie (file: visits.php). Choose the cookie expiration time to be 5 seconds in order to make easier testing the script.
References
[1] PHP Wikipedia, the free encyclopedia, May 28, 2011. [Online]. Available: http://en.wikipedia.org/wiki/PHP [2] PHP: Hypertext Preprocessor, 2011. [Online]. Available: http://pt.php.net Last visited: May 30, 2011.
Checklist
Activity Progress (%) Description 1-3 4-6 7 - 10 11 - 13 14 15 16 17 18 10 20 30 40 50 60 70 80 100 10 10 10 10 10 10 10 10 20
helloworld.php, concat.php and operators.php weekday.php, whatnumber.php and today.php whileloop.php, dowhileloop.php, forloop.php and foreachloop.php phpinfo.php, phpservervars.php and redirect.php date.php filesfun.php form.html and welcome.php computeVolume.php, callComputeVolume.php and volume.html visits.php
Handout prepared by Rui P. Rocha (DEEC-FCTUC) on June 2011, in the scope of the Databases discipline of the M.Sc. course on Electrical and Computer Engineering (MiEEC).
*
Lab Work
Page 18/18
MiEEC, DEEC-FCTUC