Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
It is a server-
side scripting language whose main purpose is to generate the HTML code, which can
be viewed by the client. As such, the PHP code itself is not visible to the clients (i.e.,
if you do a "view source" in your web browser, you cannot see the PHP code. You can
only see the resulting HTML code). This contrasts with client-side languages such as
Javascript, which is visible to the client.
PHP was first created by Rasmus Lerdorf in 1995, and saw its first official release in
1997. Milestone releases included PHP 3 in 1998, PHP 4 in 2000, and PHP 5 in 2004.
Today, many large-scale websites run on PHP. The author was first introduced to PHP
in 2000, and have found the language to be pretty easy to work with.
<?php
print "Hello World.";
?>
Executing this program on a web server enabled with PHP produces the following
output:
Hello World.
By the end of this tutorial, you should have a good understanding of the basic
constructs of PHP, as well as how PHP can interact with MySQL to produce dynamic
web pages. Please bookmark this site now by pressing Control-D and start to learn
PHP now.
Variable Types
Variables play an important role in PHP, as they are places for holding values. In
PHP, there is no need to declare variables. Variable can hold eight different data
types: bloolean, integer, float, string, array, object, resource, or NULL.
PHP is a weakly typed language. This means that variable type varies depending on
what is stored in the variable at the time. For example, if we have a variable $a,
when $a = 0, $a is an integer type variable. If later we set $a = "New", then $a
becomes a string type variable.
Variable Name
Variables in PHP are case-sensitive. For example, $Employee and $employee are two
different variables.
Variable Scope
In most cases, variables are local in scope. This means that variables declared within
a function cannot be accessed outside of the function, and variables declared outside
of a function cannot be access within the function.
The most common PHP operators are assignment operators, arithmetic operators,
combined operators, comparison operators, and logical operators. Each type is
discussed separately below.
Assignment Operators
The basic assignment operator in PHP is "=". This means that the operand to the left
of "=" gets set to the value to the right of "=".
Arithmetic Operators
Combined Operators
You can combine an arithmetic operator with the assignment operator to form a
combined operator. Combined operators are shown below:
Comparison Operators
Operator Meaning
== is equal to
!= is not equal to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
Logical Operators
Operator Meaning
|| or
&& and
and and
or or
xor xor
! not
Next: PHP IF ELSE
IF (conditional statement) {
[code if condition is true]
}
ELSE {
[code if condition is false]
}
$sample = 10;
IF ($sample > 5) {
print "Number is greater than 5";
}
ELSE {
print "Number is less than 5";
}
This is because the condition, ($sample > 5), is true. Therefore, the code in the
bracket after IF is executed.
In IF ELSE, PHP provides a way to do an either/or selection. What if you need more
than two options? This is where ELSEIF comes in. ELSEIF is built on top of the IF
ELSE construct to provide additional options. The basic syntax is as follows:
IF (conditional statement 1) {
[code if condition statement 1 is true]
}
ELSEIF (conditional statement 2) {
[code if condition statement 2 is true]
}
...
ELSE {
[code if none of the above is true]
}
ELSEIF can be repeated as many times as needed prior to the ELSE statement.
$sample = 10;
IF ($sample > 15) {
print "Level 1";
}
ELSEIF ($sample > 5) {
print "Level 2";
}
ELSE {
print "Level 3";
}
Level 2
This is because the first condition is false, and the second condition is true.
Therefore, the code in the bracket after ELSEIF is executed.
SWITCH is used in PHP to replace nested IF..ELSE loops, and is similar to the CASE
command in other computer languages. The basic syntax of SWITCH is as follows:
SWITCH ($variable) {
CASE 'value 1':
[code to execute when $variable = 'value 1']
break;
CASE 'value 2':
[code to execute when $variable = 'value 2']
break;
CASE 'value 3':
...
DEFAULT:
[code to execute when none of the CASE values matches $variable]
}
$sample = 10;
SWITCH ($sample) {
CASE 30:
print "Value is 30";
break;
CASE 25:
print "Value is 25";
break;
CASE 20:
print "Value is 20";
break;
DEFAULT:
print "Value is outside the range";
}
This is because none of the CASE conditions was matched, so the code following
DEFAULT is executed.
WHILE (expression)
{
[code to execute]
}
WHILE tells PHP to execute the [code to execute] as long as the (expression) is true.
$counter = 8;
WHILE ($counter < 10)
{
print "counter is now " . $counter . "<br>";
$counter++;
}
counter is now 8
counter is now 9
During the first iteration, $counter = 8, which means the expression, ($counter <
10), is true. Therefore, the print statement is executed, and $counter gets
incremented by 1 and becomes 9.
During the second iteration, $counter = 9, which means the expression, ($counter <
10), is true. Therefore, the print statement is executed, and $counter gets
incremented by 1 and becomes 10.
During the third iteration, $counter = 10, which means the expression, ($counter <
10), is false. Therefore, the WHILE condition no longer is true, and the code in the
bracket is no longer executed.
FOR is used in PHP to execute the same code a set number of times. The basic
syntax of FOR is as follows:
FOR tells PHP to first execute "expression 1", then evaluate "expression 2". If
"expression 2" is true, then [code to execute] is executed. After this, expression 3 is
executed, and then "expression 2" is evaluated again. If "expression 2" is true, then
[code to execute] is executed for a second time. The cycle continues until
"expression 2" is no longer true.
value is now 0
value is now 1
value is now 2
During the 1st iteration, $i = 0, which means the expression, ($i <= 2), is true.
Therefore, the print statement is executed, and $i gets incremented by 1 and
becomes 1.
During the 2nd iteration, $i = 1, which means the expression, ($i <= 2), is true.
Therefore, the print statement is executed, and $i gets incremented by 1 and
becomes 2.
During the 3rd iteration, $i = 2, which means the expression, ($i <= 2), is true.
Therefore, the print statement is executed, and $i gets incremented by 1 and
becomes 3.
During the 4th iteration, $i = 3, which means the expression, ($i <= 2), is false.
Therefore, PHP exits out of the FOR loop, and does not execute the print statement.
DO {
[code to execute]
} WHILE (conditional statement)
The difference between DO .. WHILE and WHILE is that DO .. WHILE will always
execute the [code to execute] at least once, and in a WHILE construct, it is possible
for the [code to execute] to never execute.
value is now 5
value is now 4
During the 1st iteration, $i = 5, the print statement is executed, $i gets decreased
by 1 and becomes 4, then PHP checks the expression, ($i > 3), which turns out to be
true. Therefore, the loop continues.
During the 2nd iteration, $i = 4, the print statement is executed, $i gets decreased
by 1 and becomes 3, then PHP checks the expression, ($i > 3), which is no longer
true. Therefore, PHP exits the loop.
$i = 0
DO {
print "value is now " . $i . "<br>";
$i--;
} WHILE ($i > 3);
value is now 0
Even though the expression ($i > 3) is false from the very beginning, one line is still
printed out because in DO .. WHILE, the code in the bracket following DO is always
executed at least once.
FOREACH is used in PHP to loop over all elements of an array. The basic syntax of
FOREACH is as follows:
or
FOREACH ($array_variable as $key => $value)
{
[code to execute]
}
In both cases, the number of times [code to execute] will be executed is equal to the
number of elements in the $array_variable array.
$array1 = array(1,2,3,4,5);
FOREACH ($array1 as $abc)
{
print "new value is " . $abc*10 . "<br>";
}
new value is 10
new value is 20
new value is 30
new value is 40
new value is 50
The FOREACH loop above went through all 5 elements of array $array1, and each
time prints out a statement containing 10x the array element value.
INCLUDE is used in PHP to append the code from an external file into the current file.
The syntax for INCLUDE is
INCLUDE ("external_file_name");
This is a convenient feature for a large website. Often, we may want to change an
element of the website that is consistent across the entire site, yet we don't want to
go through the trouble of updating every single file. In this case, we can simply use
INCLUDE in every file to call the same external file, and then all we need to change
is the content in that one external file.
Let's look at a simple example. Assuming we have the following two files:
index.php
<?php
print "This is the original content<br>";
include ("external_file");
?>
external_file
<?php
print "This is the external content";
?>
<?php
print "This is the original content<br>";
print "This is the external content";
?>
Next: PHP Functions
where [final_result] is typically the variable holding the final value to be returned
from the function.
function double_this_number($input_number)
{
return $input_number*2;
}
20
Next: PHP Array
An array is a way of holding multiple closely-related values, such as the test scores
of all students in a class. An array is made up of a key and a value, and the key
points to the value.
There are two types of arrays: Indexed array and Associative array. Their difference
is in the way the key is specified. Let's look at both of them:
Indexed Array
In an indexed array, the keys are numeric and starts with 0, and the values can be
any data type. The following shows two ways of assigning values to an indexed
array:
$friends = array("Sophie","Stella","Alice");
$friends[0] = "Sophie";
$friends[1] = "Stella";
$friends[2] = "Alice";
Associative Array
In an associative array, the keys are not necessarily numeric, and even when they
are numeric, not necessarily in any order. So, when you are putting data into an
associative array, you'll need to make sure you specify both the key and the value:
$student_score["John"] = 80;
$student_score["Matt"] = 90;
$student_score["May"] = 85;
Multidimensional Array
The arrays in the examples above are 1-dimensional. However, there will be times
when multidimensional arrays are desired. What's a multidimensional array? That's
when you have arrays of arrays. Let's look at an example below:
$big_array is now a 2-dimensional array. For example, if you have the following
output code:
print {$big_array[1,2]};
120
Remember to use { } when you are accessing the value of a multidimensional array.
One of the main features in PHP is the ability to take user input and generate
subsequent pages based on the input. In this page, we will introduce the mechanism
by which data is passed in PHP.
query.php
result.php
<?php
$employee_name = $_POST["employee"];
print $employee_name;
?>
After the user types in a value in the text box and click on the Submit button in
query.php, the result.php page will display the value that the user has just typed in.
How is this done? The $_POST function captures the value associated with the key
"employee", which was specified in the input name attribute in query.php. The
variable $employee_name is then set to the value for this key.
$_GET is $_POST's closely related cousin. The usage is exactly the same, except
you'll need to use $_GET if the form action type is GET. When the form action type is
GET, the parameters you submitted will be visible in the URL as the query string. In
a POST method, no query string is visible in the URL.
Usually when using $_POST or $_GET, you'll want to first check to see if PHP has
indeed received values for the key of interest. If not, you may want to assign the
receiving variable some type of default value. To do this, we leverage the isset()
function:
$result_variable = isset($_POST["key_value"],0,$_POST["key_value"]);
Common input methods include text input, radio button, checkbox, and drop down
menu.
If you have a website, you may wish to set a cookie on the client computer so that
your site will remember that user when she returns. PHP provides ways to create,
retrieve, and delete cookies.
Create cookies
Cookies are set using the setcookie() function. The syntax is as follows:
All arguments except name are optional. Unix time is the number of seconds that
have elapsed since January 1, 1970.
You must make sure that the setcookie() function is called before any HTML output is
printed.
Let's take a look at a couple of examples:
<?php
setcookie('cookie1','lisa');
?>
This sets up a cookie with name = "cookie1" and value = "lisa". As expire time is not
specified, this cookie will expire when the browser is closed.
<?php
setcookie('cookie2','electric1',time()+3600);
?>
This sets up a cookie with name = "cookie2" and value="electric1", and this cookies
expires in 1 hour (3600 second).
Retrieve cookies
Delete cookies
To delete a cookie from a client computer, simply use the setcookie() function and
set the expiration time as a time in the past. For example, the following code,
<?php
setcookie('cookie1','lisa',1);
?>
will get rid of the cookie with name = "cookie1" and value = "lisa".
If you have moved your pages, you can use PHP to perform a redirect to your new
page.
The search engine friendly way of redirecting is the 301 redirect. In PHP, this is
implemented as follows:
<?
Header("HTTP/1.1 301 Moved Permanently");
Header("Location:http://www.new-site.com");
?>
Make sure the above code is included before any HTML is produced. Otherwise, the
redirect will not work.
A 301 redirect directs the search engine spiders to the new page, and ensures that
all link juices to your old page are all passed to the new page.
Please note that if you do not include the first Header line above, the redirect still
works. But, instead of a 301 redirect, now it becomes a 302 (temporary) redirect.
302 redirects are not search engine friendly, as it has become a common spam
technique. So, if you want to ensure your search engine ranking is not affected by
moving your file elsewhere or changing your file name, make sure you set up a 301
redirect.
Here we give an example of the PHP code that will read data out of a MySQL
database and present it in a nice tabular format in HTML.
Table Employee
Name Salary
Lisa 40000
Alice 45000
Janine 60000
The PHP code needed is as follows (assuming the MySQL Server sits in localhost and
has a userid = 'cat' and a password of 'dog', the database name is 'myinfo') :
while ($row=mysql_fetch_row($result))
{
print "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
print "</table>";
Output is
Employee Information
These two lines tell PHP how to connect to the MySQL server.
while ($row=mysql_fetch_row($result))
{
print "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
$row[0] denotes the first column of the query result, namely the "name" field, and
$row[1] denotes the second column of the query result, namely the "salary" field.
The . in the print statement is the concatenation operator, and acts to combine the
string before and string after together. The print statement continuess until all 3
rows have been fetched.
This pages lists common PHP commands and their respective syntax. To view details
on each command, please click on the link; to learn PHP from the beginning, please
go to the PHP Tutorial homepage.
DO ... WHILE
DO {
[code to execute]
} WHILE (conditional statement)
ELSEIF
IF (conditional statement 1) {
[code if condition statement 1 is true]
}
ELSEIF (conditional statement 2) {
[code if condition statement 2 is true]
}
ELSE {
[code if neither statement is true]
}
FOR Loop
FOREACH Loop
IF ELSE
IF (conditional statement) {
[code if condition is true]
}
ELSE {
[code if condition is false]
}
Include
INCLUDE ("external_file_name");
<B.SWITCH< b>
SWITCH ($variable) {
CASE 'value 1':
[code to execute when $variable = 'value 1']
break;
CASE 'value 2':
[code to execute when $variable = 'value 2']
break;
CASE 'value 3':
...
DEFAULT:
[code to execute when none of the CASE values matches $variable']
}
WHILE Loop
WHILE (expression)
{
[code to execute]
}
Next: Resources