PHP Tutorial
To open a block of PHP
code in a page you can use one of these four sets of opening and closing tags
Opening
Tag |
Closing
Tag |
<? |
?> |
<?php |
?> |
<% |
%> |
<script
language="php"> |
</script> |
The first pair (<? and ?>) is called short tags. You
should avoid using short tags in your application especially if it's meant to
be distributed on other servers. This is because short tags are not always supported
( though I never seen any web host that don't support it ). Short tags are only
available only explicitly enabled setting the short_open_tag value to On in the PHP configuration file php.ini.
So, for all PHP code in
this website I will use the second pair, <?php
and ?>.
Now, for the first
example create a file named hello.php ( you can use NotePad or your
favorite text editor ) and put it in your web servers root directory. If you
use Apache the root directory is APACHE_INSTALL_DIR\htdocs, with APACHE_INSTALL_DIR is the directory where you install Apache. So if you
install Apache on C:\Program
Files\Apache Group\Apache2\htdocs then you put hello.php in C:\Program Files\Apache
Group\Apache2\htdocs
Example : hello.php
Source code : hello.phps
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "<p>Hello
World, How Are You Today?</p>";
?>
</body>
</html>
To view the result
start Apache then open your browser and go to http://localhost/hello.php or http://127.0.0.1/hello.php. You should see something like this in your browser window.
The example above shows
how to insert PHP code into an HTML file. It also shows the echo statement used to output a string.
See that the echo statement ends with a semicolon.
Every command in PHP must end with a semicolon. If you forget to use semicolon
or use colon instead after a command you will get an error message like this
Parse error: parse
error, unexpected ':', expecting ',' or ';' in
c:\Apache\htdocs\examples\get.php on line 7
However in the hello.php example above omitting the semicolon
won't cause an error. That's because the echo statement was immediately followed by a closing tag.
Comment is a part of
your PHP code that will not be translated by the PHP engine. You can use it to
write documentation of your PHP script describing what the code should do. A
comment can span only for one line or span multiple line.
PHP support three kinds
of comment tags :
1.
//
This is a one line comment
2.
#
This is a Unix shell-style comment. It's also a one line comment
3.
/* ..... */
Use this multi line comment if you need to.
Example : comments.php
Source code : comments.phps
<?php
echo "First line <br>"; //
You won't see me in the output
// I'm a one liner comment
/*
Same thing, you won't
see this in the output file
*/
echo "The above comment spans two lines <br>";
#
Hi i'm a Unix shell-style comment
# Too bad you can't see me
echo "View the source of this file, you'll see no comments here
<br>";
?>
Variables in PHP are
represented by a dollar sign followed by the name of the variable. The variable
name is case-sensitive,
so $myvar is different from $myVar.
A valid variable name
starts with a letter or underscore, followed by any number of letters, numbers,
or underscores.
Example :
<?php
$myvar =
"Hello"; // valid
$yourVar_is-123 = "World"; // valid
$123ImHere = "Something"; //
invalid, starts with number
?>
The scope of a variable
is the context within which it is defined. Basically you can not access a
variable which is defined in different scope.
The script below will
not produce any output because the function Test() declares no $a variable. The echo statement looks for a local version of the $a variable, and it has not been
assigned a value within this scope. Depending on error_reporting value in php.ini the script below will print nothing or issue an error
message.
Example : scope.php
Source code : scope.phps
<?php
$a = 1; // $a is a global variable
function
Test()
{
echo $a;
// try to print $a, but $a is not defined here
}
Test();
?>
If you want your global
variable (variable defined outside functions) to be available in function scope
you need to use the$global
keyword. The code
example below shows how to use the $global keyword.
Example : global.php
Source code : global.phps
<?php
$a = 1; // $a is defined in global scope ...
$b = 2; // $b too
function
Sum()
{
global $a,
$b; // now $a and $b are available in Sum()
$b = $a + $b;
}
Sum();
echo $b;
?>
Superglobals are
variables that available anywhere in the program code. They are :
§
$_SERVER
Variables set by the web server or otherwise directly related to the execution
environment of the current script. One useful variable is $_SERVER['REMOTE_ADDR'] which you can use to know you
website visitor's IP address
Example : ip.php
Source code : ip.phps
Your computer IP is
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
§
$_GET
Variables provided to the script via HTTP GET. You can supply GET variables
into a PHP script by appending the script's URL like this : http://www.php-mysql-tutorial.com/../examples/get.php?name=php&friend=mysql
or set the a form method as method="get"
Example: get.php
Source code : get.phps
<?php
echo "My name is {$_GET['name']} <br>";
echo "My friend's name is {$_GET['friend']}";
?>
Note that I put $_GET['name'] and
$_GET['friend'] in
curly brackets. It's necessary to use these curly brackets when you're trying
to place the value of an array
into a string.
You can also split the string like this :
echo "My name is " . {$_GET['name']} .
"<br>"; but it is easier to put the curly brackets.
§
$_POST
Variables provided to the script via HTTP POST. These comes from a form which
set method="post"
§
$_COOKIE
Variables provided to the script via HTTP cookies.
§
$_FILES
Variables provided to the script via HTTP post file uploads. You can see the
example in
Uploading files to MySql Database
§
$_ENV
Variables provided to the script via the environment.
§
$_REQUEST
Variables provided to the script via the GET, POST, and COOKIE input
mechanisms, and which therefore cannot be trusted. It's use the appropriate $_POST or $_GET from your script instead of using $_REQUEST so you will always know that a
variable comes from POST or GET.
§
$GLOBALS
Contains a reference to every variable which is currently available within the
global scope of the script.
You usually won't need
the last three superglobals in your script.
PHP supports eight
primitive types.
Four scalar types:
§
boolean
: expresses truth value, TRUE or FALSE. Any non zero values and non empty
string are also counted as TRUE.
§
integer
: round numbers (-5, 0, 123, 555, ...)
§
float
: floating-point number or 'double' (0.9283838, 23.0, ...)
§
string
: "Hello World", 'PHP and MySQL, etc
Two compound types:
§
array
§
object
And finally two special
types:
§
resource
( one example is the return value of mysql_connect() function)
§
NULL
In
PHP an array can have numeric key, associative key or both. The value of an
array can be of any type. To create an array use the array() language construct like this.
Example : array.php
Source code : array.phps
<?php
$numbers = array(1, 2, 3, 4, 5, 6);
$age = array("mom" => 45, "pop" => 50,
"bro" => 25);
$mixed = array("hello" => "World", 2 => "It's
two";
echo "numbers[4] = {$numbers[4]} <br>";
echo "My mom's age is {$age['mom']} <br>";
echo "mixed['hello'] = {$mixed['hello']} <br>";
echo "mixed[2] = {$mixed[2'}";
?>
When working with
arrays there is one function I often used. The print_r() function. Given an array this function will print the values
in a format that shows keys and elements
Example : printr.php
Source code : printr.phps
<?php
$myarray = array(1, 2, 3, 4, 5);
$myarray[5] = array("Hi", "Hello", "Konnichiwa",
"Apa Kabar");
echo
'<pre>';
print_r($myarray);
echo '</pre>';
?>
Don't forget to print
the preformatting tag <pre> and </pre> before and after calling print_r(). If you don't use them then you'll have to view the page
source to see a result in correct format.
In PHP you don't need
to explicitly specify a type for variables. A variable's type is determined by
the context in which that variable is used. That is to say, if you assign a
string value to variable $var, $var becomes a string. If you then assign
an integer value to $var, it becomes an integer.
An example of PHP's
automatic type conversion is the addition operator '+'. If any of the operands
is a float, then all operands are evaluated as floats, and the result will be a
float. Otherwise, the operands will be interpreted as integers, and the result
will also be an integer. Note that this does NOT change the types of the
operands themselves; the only change is in how the operands are evaluated.
Example :
<?php
$myvar = "0"; // $myvar is string (ASCII 48)
$myvar += 2; // $myvar is now an integer (2)
$myvar = $foo + 1.3; // $myvar is now a float (3.3)
$myvar = 5 + "10 Piglets"; // $foo is integer (15)
?>
To cast a variable
write the name of the desired type in parentheses before the variable which is
to be cast.
Example : casting.php
Source code : casting.phps
<?php
$abc = 10; // $abc is an integer
$xyz = (boolean) $abc; // $xyz is a boolean
echo
"abc is $abc and xyz is $xyz <br>";
?>
The casts allowed are:
§
(int),
(integer) - cast to integer
§
(bool),
(boolean) - cast to boolean
§
(float),
(double), (real) - cast to float
§
(string)
- cast to string
§
(array)
- cast to array
§
(object)
- cast to object
Strings are probably
what you will use most in your PHP script. From concatenating, looking for
patterns, trim, chop etc. So I guess it's a good idea to take a better look at
this creature. We will also take a peek at some string functions that you might
find useful for everyday coding.
To declare a string in
PHP you can use double quotes ( " ) or single quotes ( ' ). There are some
differences you need to know about using these two.
If you're using
double-quoted strings variables will be expanded ( processed ). Special
characters such as line feed ( \n ) and carriage return ( \r ) are expanded
too. However, with single-quoted strings none of those thing happen. Take a look
at the example below to see what I mean.
Note that browsers
don't print newline characters ( \r and \n ) so when you open string.php
take a look at the source and you will see the effect of these newline
characters.
Example : string.php
Source code : string.phps
<?php
$fruit = 'jamblang';
echo
"My favourite fruit is $fruit <br>";
echo 'I lied, actually I hate $fruit <br>';
echo
"\r\n My first line \r\n and my second line <br>\r\n";
echo ' Though I use \r\n this string is still on one line <br>';
?>
To concat two strings
you need the dot ( . ) operator so in case you have a long string and for the
sake of readability you have to cut it into two you can do it just like the
example below.
Actually if you need to
write a loong string and you want to write it to multiple lines you don't need
concat the strings. You can do it just like the second example below where $quote2 is split into three lines.
Example : concat.php
Source : concat.phps
<?php
$quote1
= "Never insult Dumbledore " .
"in front of
me!";
$quote2
= "Nami,
you are
my nakama!";
echo
$quote1 . "<br>";
echo $quote2;
?>
<?php
//
print '12'
echo substr('123456789', 0, 2);
//
print '56789'
echo substr('123456789', 4);
//
print '89'
echo substr('123456789', -2);
//
print '456'
echo substr('123456789', 3, -4);
?>
For example if you want
to print a series of ten asteriks ( * ) you can do it with a for loop like this
:
<?php
for ($i = 0; $i < 10; $i++) {
echo '*';
}
?>
Or you can go the easy
way and do it like this :
<?php
echo str_repeat('*', 10);
?>
For example: you want
to get the file extension from a file name. You can use this function in
conjunction with substr()
<?php
$ext = substr(strrchr($filename, '.'), 1);
?>
What the above code do
is get a chunk of $filename starting from the last dot in $filename then get the substring of it
starting from the second character ( index 1 ).
To make things clearer
suppose $filename is 'tutorial.php'. Using strrchr('tutorial.php', '.') yield '.php' and after substr('.php', 1) we get the file extension; 'php'
<?php
// print 'abc def'
echo trim(' abc def ');
?>
This function is
usually used on form values before being used for database queries. You will
see this function used a lot in this tutorial ( like this one
) so there's no need to present an example here.
This function is
commonly used to extract values in a string which are separated by a a certain
separator string. For example, suppose we have some information stored as comma
separated values. To extract each values we ca do it like shown below
<?php
// extract information from comma separated values
$csv = 'Uzumaki Naruto,15,Konoha Village';
$info
= explode(',', $csv);
?>
Now, $info is an array with three values :
Array
(
[0] => Uzumaki Naruto
[1] => 15
[2] => Konoha Village
)
We can further process
this array like displaying them in a table, etc.
This one do the
opposite than the previous function. For example to reverse back the $info array into a string we can do it
like this :
<?php
$info = array('Uzumaki Naruto', 15, 'Konoha Village');
$csv
= implode(',', $info);
?>
Another example :
Pretend we have an array containing some values and we want to print them in an
ordered list. We can use the implode() like this :
<?php
// print ordered list of names in array
$names
= array('Uchiha Sasuke', 'Haruno Sakura', 'Uzumaki Naruto', 'Kakashi');
echo
'<ol><li>' . implode('</li><li>', $names) .
'</li></ol>';
?>
The result of that code
is like an ordered list just like shown below
1.
Uchiha
Sasuke
2.
Haruno
Sakura
3.
Uzumaki
Naruto
4.
Kakashi
By the way, i did write
the above php code to print that list instead of writing the list directly
When displaying numbers
it's usuallly more readable if the numbers is properly formatted like 1,234,567
instead of 1234567. Using this function is very simple like shown below
<?php
// display 15,120,777
echo number_format(15120777);
?>
The next examples will
show you how to use control structures in PHP. I won't go through all just the
ones that i will use in the code examples in this site. The control structures
are
§
if
§
else
§
while
§
for
The if statement evaluates the truth value
of it's argument. If the argument evaluate as TRUE the code following the if statement will be executed. And if
the argument evaluate as FALSE and there is an else statement then the code following the else statement will be executed.
Example : visitor-
info.php
Source code : visitor-info.phps
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
if(strpos($agent, 'Opera') !== false)
$agent = 'Opera';
else if(strpos($agent, "MSIE") !== false)
$agent = 'Internet Explorer';
echo "Your computer IP is $ip and you are using $agent";
?>
The strpos() function returns the numeric
position of the first occurrence of it's second argument ('Opera') in the first
argument ($agent). If the string 'Opera' is found inside
$agent, the function returns the position
of the string. Otherwise, it returns FALSE.
When you're using
Internet Explorer 6.0 on Windows XP the value of $_SERVER['HTTP_USER_AGENT'] would be something like:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
and if you're using
Opera the value the value may look like this :
Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.0 [en]
So if i you use Opera
the strpos() function will return value would be
61. Since 61 !==
false then the
first if statement will be evaluated as true
and the value of $agent will be set to the string 'Opera'.
Note that I use the !== to specify inequality instead of != The reason for this is because if the
string is found in position 0 then the zero will be treated as FALSE, which is
not the behaviour that I want.
The while() statement
is used to execute a piece of code repeatedly as long as the while expresssion
evaluates as true. For example the code below will print the number one to
nine.
Example : while.php
Source code : while.phps
<?php
$number = 1;
while
($number < 10)
{
echo $number . '<br>';
$number += 1;
}
?>
You see that I make the
code $number += 1; as bold. I did it simply to remind
that even an experienced programmer can sometime forget that a loop will
happily continue to run forever as long as the loop expression ( in this case $number < 10 ) evaluates as true. So when you're
creating a loop please make sure you already put the code to make sure the loop
will end in timely manner.
The break statement is used to stop the
execution of a loop. As an example the while loop below will stop when $number equals to 6.
Example : break.php
Source code : break.phps
<?php
$number = 1;
while
($number < 10)
{
echo $number . '<br>';
if
($number == 6)
{
break;
}
$number += 1;
}
?>
You can stop the loop
using the break statement. The break statement
however will only stop the loop where it is declared. So if you have a
cascading while loop and you put a break statement in the inner loop then only
the inner loop execution that will be stopped.
Example : break2.php
Source code : break2.phps
<?php
$floor = 1;
while
($floor <= 5)
{
$room = 1;
while
($room < 40)
{
echo "Floor : $floor, room number :
$floor". "$room <br>";
if
($room == 2)
{
break;
}
$room += 1;
}
$floor += 1;
echo "<br>";
}
?>
If you run the example
you will see that the outer loop, while ($floor <= 5), is executed five times and the inner
loop only executed two times for each execution of the outer loop. This proof
that the break statement only stop the execution of the inner loop where it's
declared.
The for loop syntax in
PHP is similar to C. For example to print 1 to 10 the for loop is like this
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i . '<br>';
}
?>
A more interesting
function is to print this number in a table with alternating colors. Here is
the code
Example : alternate-colors.php
Source : alternate-colors.phps
<table
width="200" border="0" cellspacing="1"
cellpadding="2">
<tr>
<td bgcolor="#CCCCFF">Alternating row colors</td>
</tr>
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2) {
$color = '#FFFFCC';
} else {
$color = '#CCCCCC';
}
?>
<tr>
<td bgcolor="<?php echo $color; ?>"><?php echo $i;
?></td>
</tr>
<?php
}
?>
</table>
This code display
different row colors depending on the value of $i. If $i is not divisible by
two it prints yellow otherwise it prints gray colored rows.
Real world applications
are usually much larger than the examples above. In has been proven that the
best way to develop and maintain a large program is to construct it from
smaller pieces (functions) each of which is more manageable than the original program.
A function may be
defined using syntax such as the following:
<?php
function addition($val1, $val2)
{
$sum = $val1 + $val2;
return $sum;
}
?>
When calling a function
you usually provide the same number of argument as in the declaration. Like in
the function above you usually call it like this :
$result = addition(5, 10);
But you can actually
call a function without providing all the arguments by using default parameters.
Example : default-param.php
Source code : default-param.phps
<?php
function
repeat($text, $num = 10)
{
echo "<ol>\r\n";
for($i = 0; $i < $num; $i++)
{
echo "<li>$text
</li>\r\n";
}
echo "</ol>";
}
//
calling repeat with two arguments
repeat("I'm the
best", 15);
//
calling repeat with just one argument
repeat("You're the
man");
?>
Function repeat() have two arguments $text and $num. The $num
argument has a default value of 10. The first call to repeat() will print the text 15 times because
the value of $num will be 15. But in the second call
to repeat() the second parameter is omitted so repeat() will use the default $num value of 10 and so the text is
printed ten times.
Applications are
usually a sequence of functions. The result from one function is then passed to
another function for processing and so on. Returning a value from a function is
done by using the return
statement.
Example : return.php
Source code : return.phps
<?php
$myarray = array('php tutorial',
'mysql
tutorial',
'apache
tutorial',
'java
tutorial',
'xml
tutorial');
$rows = buildRows($myarray);
$table = buildTable($rows);
echo $table;
function
buildRows($array)
{
$rows = '<tr><td>' .
implode('</td></tr><tr><td>',
$array) .
'</td></tr>';
return $rows;
}
function
buildTable($rows)
{
$table = "<table cellpadding='1' cellspacing='1'
bgcolor='#FFCC00'
border='1'>$rows</table>";
return
$table;
}
?>
You can return any type
from a function. An integer, double, array, object, resource, etc.
Notice that in buildRows() I use the built in function implode(). It joins all elements of $array with the string '</td></tr><tr><td>' between each element. I also use
the '.' (dot) operator to concat the
strings.
You can also write buildRows() function like this.
<?php
...
function buildRows($array)
{
$rows
= '<tr><td>';
$n
=
count($array);
for($i
= 0; $i < $n - 1; $i++)
{
$rows
.= $array[$i] . '</td></tr><tr><td>';
}
$rows
.= $array[$n - 1] . '</td></tr>';
return $rows;
}
...
?>
Of course it is more
convenient if you just use implode().