Professional Documents
Culture Documents
Starting of PHP With Simplest Codes and Examples
Starting of PHP With Simplest Codes and Examples
What is PHP?
Hypertext Pre-processor (PHPs) is a server-side scripting language, and server-sidescripts are special
commands you must place in Web pages. Those commands are processed before the pages are sent from
your Server to the Web browser of your visitor. A typical PHP files will content commads to be executed
in the server in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags.
When you type a URL in the Address box or click a link on a Web page, you're asking a Web server on a
computer somewhere to send a file to the Web browser (sometimes called a "client") on your computer. If
that file is a normal HTML file, it looks exactly the same when your Web browser receives it as it did
before the Web server sent it. After receiving the file, your Web browser displays its contents as a
combination of text, images, and sounds. In the case of an PHP page, the process is similar, except there's
an extra processing step that takes place just before the Web server sends the file. Before the Web server
sends the PHP file to the Web browser, it runs all server-side scripts contained in the page. Some of these
scripts display the current date, time, and other information. Others process information the user has just
typed into a form, such as a page in the Web site's guestbook
To distinguish them from normal HTML pages, PHP files are usually given the ".php" extension.
1
Creating my first PHP file
In this page we will add PHP scripting languaje codes to our regular HTML page, we will learn how to
write texts and how to concatenete them and write some special characters, and we will start using
variables.
In our fisrt step to learn PHP scripting languaje we will modify a regular HTML page and we will add to it
PHP commads. Bellow we will find a regular HTML page:
mypage.html
<html>
<head>
<title>This is my page</title>
</head>
<body>
This is the content of my page.
</body>
</html>
To create a PHP page using the page above as our model, the first important action is to rename our file. In
our case we will name the file "mypage.php". When a file with ".php" extension is placed in the server
and the corresponding url is visited, the server will process the file before sending it to the client, so that
all PHP commands will be processed. We may just change the name of our file as propoused and save it
to our server (without any additional changes), and when visiting the corresponding URL the result will be
exactly the same (because there is nothing to be processed in the page) .
To this renamed page ("mypage.php") we will add a small PHP command within <?php opening tag and
?> closing tag.
mypage.php
<html>
<head>
<title>This is my page</title>
</head>
<body>
This is the content of my page.
<?php
print "Do you like it?";
?>
</body>
</html>
2
When visiting the page, the server will process the page to execute all PHP commands in the page, which
will be located within <?php opening tag and ?> closing tags. In our case "print" command will write
to the resulting page the text contained between brakets ("Do you like it?"). Often, instead of print
command, echo command is used to output string. At the end of the line we will add ";" (otherway we
will get an error). We may use "echo" command instead of "print", and the result will be identical.
We may also include all the php commands in one line by placing the code bellow in our page.
Between opening and closing tags we may include several lines with executable commands as shown
bellow (we must write ";" at the end of each line):
mypage.php
<html>
<head>
<title>This is my page</title>
</head>
<body>
This is the content of my page.
<?php
print "Do you like it?";
print "<br>";
print "<b>If not, please visit a different page.</b>";
print "<br>";
print "<h1>Goodbay</h1>";
?>
</body>
</html>
Additionaly we may add several opening and closing tags within our page with executable commands.
3
mypage.php
<html>
<head>
<title>This is my page</title>
</head>
</body>
</html>
As sown in the example above we may add PHP scripts within HTML tags.
Concatenation of strings
Check the codes bellow:
Code 1
<?php
print "Hello!<br>";
print "I am Joe";
?>
Code 2
<?php
print "Hello!<br>"."I am Joe";
?>
The pages containing any of the codes above will be exactly the same. We have just put both lines in one,
and to do that we have use a point between the two texts we want to show in our pages. The point used in
Code 2 will concatenated both strings.
4
Writing some special characters
Check the codes bellow:
The Code The output
Use "\n" to add a line break Use "\n" to add a line break
AA
<pre> BB
<?php CC
print "AA\nBB\nCC\nDD\nEE"; DD
?> EE
</pre>
Use "\"" to add brakets<br> Use "\"" to add brakets
<?php He said "Hello" to John
print "He said \"Hello\" to John";
?>
mypage.php
<?php
$my_name="Joe";
$my_hello_text="Hello everybody!";
$year_create=2002;
?>
<html>
<head>
<title>This is <?php print $my_name; ?>´spage</title>
</head><body>
<?php print $my_hello_text; ?>
5
In this example, we have defined three variables (line 2, 3 and 4) and we have included the information in
the variable latter within the HTML code.
Check those variables carefully: $my_name, $my_hello_text and $year_create has not been defined in
advance (we have add a value to the variables the first time they have used them in the file, without
letting know the program we will used it in advance), and the values do not contain the same kind of
content:
6
PHP tutorial: Displaying Date and Time
The date and time we will show how to display in this tutorial is the one specified by the server which is
hosting our pages. In case you want to display a different date or time (p. e., your clients are mostly from
Belgium but your server is located in US and you want to display the local time in Belgium) you will find
how to do it latter on this page.
In the table bellow we have include the PHP code necessary to display one by one all the time and date
related information. By copying the code in the first column to your page you will get the data which is
explained in the third column. The column in the middle is the value of those data the day we were
preparing this page.
Code Output
<?php print date("a"); ?> pm "am" or "pm"
<?php print date("A"); ?> PM "AM" or "PM"
<?php print date("d"); ?> 15 Day of the month: 01 to 31
<?php print date("D"); ?> Tue Day of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat
<?php print date("F"); ?> OctoberMonth: January, February, March...
<?php print date("h"); ?> 03 Hour: 01 to 12
<?php print date("H"); ?> 15 Hour: 00 to 23
<?php print date("g"); ?> 3 Hour: 1 to 12
<?php print date("G"); ?> 15 Hour: 0 to 23
<?php print date("i"); ?> 26 Minutes: 00 to 59
<?php print date("j"); ?> 15 Day of the month: 1 to 31
<?php print date("l"); ?> TuesdayDay of the week: Sunday, Monday, Tuesday...
<?php print date("L"); ?> 0 Is it a leap year? 1 (yes) or 0 (no)
<?php print date("m"); ?> 10 Month: 01 to 12
<?php print date("n"); ?> 10 Month: 1 to 12
<?php print date("M"); ?> Oct Month: Jan, Feb, Mar, Apr, May...
<?php print date("s"); ?> 03 Seconds: 00 to 59
Ordinal: 1st, 2st, 3st, 4st... Need to be used with a numeric
<?php print date("S"); ?> th
time/date value. See latter.
<?php print date("t"); ?> 31 Number of days in the month: 28 to 31
<?php print date("U"); ?> 1034691963 Seconds since 1970/01/01 00:00:00
<?php print date("w"); ?> 2 Day of the week: 0 (Sunday) to 6 (Saturday)
<?php print date("Y"); ?> 2002 Year (four digits)
<?php print date("y"); ?> 02 Year (two digits)
<?php print date("z"); ?> 287 Day of the year: 0 to 365
<?php print date("Z"); ?> -21600 Difference in seconds from Greenwhich meridian
7
As shown in the table the commands we are using in all case are "print" (in order to show the values to the
visitor) and "date" (which will allow us to get the data corresponding to the string code we are using
between brakets).
So we already know how to obtain the data and how to show it in our page, but if we want to display
different values simultaneously, we have at least three option:
The first option is very easy to understand (we have just copied the code from the table one by one). The
second option concatenates the data basically in the same way, and the third one is probably the most
useful system, but the one we must understand before using it.
Command "date" will get the data we want to display, and that data is specified by the string used within
data (in our case: "Y:m:d"). Each character in this string may or may not have a meaning depending upon
there is or there is not a value asociate with that letter (see the first table in this page). In our case some
characters will be replaced by its corresponding value:
Y - Year (four digits)
. no meaning
m - Month 1 to 12
. no meaning
D - day of month 1 to 31
Take care when using date command or you may get unwanted data as shown in the first row in the table
bellow (use the code in second row instead):
The Code The output Character with meaning
<?php print date("Today is l"); ?> WETo15pm02 2603 The following characters have a meaning:
Tuesday T, d, a, y, i, s, l
<?php print "Today is ".date("l"); ?> Today is Tuesday Only data asociated to "l" (day of the
week) is requested
8
Example: Link of the Day
What if you wanted to have a link that points to a different page every day of the week? Here's how you
can do that. First, create one page for each day of the week and name them "Sunday.htm," "Monday.htm,"
and so on.
First we must know the time in the server. We will create a text file with the code bellow, and we will copy
it to our server:
Then we will visit our page and we will get the time in the server. Let suppose the time is 16:00
Second, we will calculate the difference in hours between local time and the time in server. Let suppose
the time in Belgium is 20:00, so the difference is 4 hours.
To get the local time we will use the code in the table bellow:
<?php
$differencetolocaltime=4;
$new_U=date("U")-$differencetolocaltime*3600;
print date("H:i", $new_U);
?>
9
Lets explain this code:
• We have create a variable named $differencetolocaltime, and we have stablish the value for this
variable (4)
• In third line of the script we have create a variable named $new_U, and the value for this variable
will be 'date("U")' (Seconds since 1970/01/01 00:00:00) to which we have substracted the
difference of hours between the two time zones (in our case 4 hours, which is the value for the
variable $differencetolocaltime, has been multiplied by 3600, which is the number of seconds in
one hour)
• In the last step we have write to the document the new hour and time by using "date" command to
which we have let know the exact date (specified by $new_U) from which we want to get the time
(if it is not specified, as for example when using 'date("H:i")', the time and date in the server will
be displayed as shown before in this page).
GET and POST methods and how to get info from them
There are two ways we may get info from users by using a form: GET and POST methods. Additionally,
GET method may be used for other porpoises as a regular link. Let´s check both methods
Post method
Get method
An example: three versions
POST method
This method will be indicated in the form we are using to get information from user as shown in the
example bellow
When submitting the form we will visit the URL bellow (will be different when using GET method):
http://www.phptutorial.info/learn/GetandPost.php
When getting information from the form in the response page we will use $_POST command
10
Code Output
<?php print $_POST["thename"]; ?> John
<?php print $_POST["theage"]; ?> 30
<?php Hi John, I know you are 30 years old
$thename=$_POST["thename"];
$theage=$_POST["thename"];
GET method
This method may be used exactly as in the example above, but the URL we will visit after submission will
be diferent.
In the example bellow we have removed the word "POST" and "GET" has been written instead.
http://www.phptutorial. info/learn/GetandPost.php?thename=John&theage=30
When getting information from the form in the response page we will use $_GETcommand.
Code Output
<? print $QUERY_STRING; ?> thename=John&theage=30
<?php print $_GET["thename"]; ?> John
<?php print $_GET["theage"]; ?> 30
<?php Hi John, I know you are 30 years old
$thename=$_GET["thename"];
$theage=$_GET["thename"];
11
An example: three versions
Get method may be used for additonal porposes. Although Post method is not used in this example, a
similar page may be create. In the example bellow it is shown data in different ways depending
on $QUERY_STRING or $_GET values obtained from the the url visited.
Getandpostexample.php
Getandpostexample.php
<html>
<body bgcolor=FFFFFF>
<pre>
<b>Information about my friends</b>
<?php } ?>
</pre>
</body>
</html>
12
The previous code and this one will produce the same result. Just compare them: instead of using open and
close tags each time, print command is used. Line breaks ("\n") are included within the text to be printed.
Getandpostexample2.php
<?php
// this code is always shown
print "<html>\n<body bgcolor=FFFFFF>\n";
print "<pre>\n<b>Information about my friends</b>\n";
if ($QUERY_STRING=="showall") {
print "\nAnna\n From London. Student";
print "\nPaolo\n From Roma. Student";
print "\nAndoni\n From Euskadi. Student";
print "\n<a href=Getandpostexample.php>Hide data</a>";
}else{
if ($_GET["name"]=="Anna") {
print "\nAnna\n From London. Student";
}else{
print "\n<a href=Getandpostexample.php?name=Anna>Anna</a>";
}
if ($_GET["name"]=="Paolo") {
print "\nPaolo\n From Roma. Student";
}else{
print "\n<a href=Getandpostexample.php?name=Paolo>Paolo</a>";
}
if ($_GET["name"]=="Andoni") {
print "\nAndoni\n From Euskadi. Student";
}else{
print "\n<a href=Getandpostexample.php?name=Andoni>Andoni</a>";
}
?>
</pre>
</body>
</html>
13
his third version uses three variables named $Anna, $Paolo and $Andoni, which are defined in first tree
lines of the code. Using variables may be a very interesting option in cases like this one.
Getandpostexample3.php
<?php
// Variables are defined for each person
$Anna = "\nAnna\n From London. Student";
$Paolo = "\nPaolo\n From Roma. Student";
$Andoni = "\nAndoni\n From Euskadi. Student";
if ($QUERY_STRING=="showall") {
print $Anna.$Paolo.$Andoni;
print "\n<a href=Getandpostexample.php>Hide data</a>";
}else{
if ($_GET["name"]=="Anna") {
print $Anna;
}else{
print "\n<a href=Getandpostexample.php?name=Anna>Anna</a>";
}
if ($_GET["name"]=="Paolo") {
print $Paolo;
}else{
print "\n<a href=Getandpostexample.php?name=Paolo>Paolo</a>";
}
if ($_GET["name"]=="Andoni") {
print $Andoni;
}else{
print "\n<a href=Getandpostexample.php?name=Andoni>Andoni</a>";
}
}
?>
</pre>
</body>
</html>
14
PHP tutorial: Using arrays
Introduction
Working with Arrays
Selecting values from a array
Creating a table from data in a string
Simple keyword search
Introduction
Instead of having our information (variables or numbers) in variables like $Mydata1, $Mydata2,
$Mydata3 etc, by using arrays our information may be contained in an unique variable. Very often, we will
create an array from data obtained from a table with only one column. Let´s check an example:
array.asp
<html> 1 Original table for the array in the script
<title>My Array</title> 2
<body> 3
MyData
4
<?php 5 0 1
$MyData [0] = "0" 6
$MyData [1] = "1" 7 1 4
$MyData [2] = "2" 8
$MyData [3] = "3" 9 2 7
$MyData [4] = "4" 10 3 3
$MyData [5] = "5"
$MyData [6] = "6" 11 4 4
$MyData [7] = "7" 12
$MyData [8] = "8" 5 5
$MyData [9] = "9" 13
6 6
print $MyData [5]; 14 7 7
?>
15 8 8
</body>
</html> 16 9 9
In the response page we will print the
value assigned to $MyData [5] in the array. The response
17
page will return 5.
18
19
20
21
15
An array may be created from a two dimentional table. Let´s check an example:
array2.php
<html> We may consider the table bellow as the source of
<title>My Array</title> information to create an array named $Mydata.
<body>
MyData 0 1 2
<?php
$MyData [0][0] = "1"; 0 1 2 3
$MyData [0][1] = "2";
$MyData [0][2] = "3"; 1 4 5 6
$MyData [1][0] = "4";
$MyData [1][1] = "5"; 2 7 8 9
Lines 6-14. Values have assigned to
$MyData [1][2] = "6"; the array.
$MyData [2][0] = "7";
$MyData [2][1] = "8"; Line 16. In the response page we will send the value
$MyData [2][1] = "9"; assigned to $MyData [1][2] in the array. The first number
will be the row and the second one the column, so that in our
print $MyData [1][2]; case the response page will show the value "6"
?>
</body>
</html>
An array may be created from a two dimentional table. Let´s check an example:
array2.php
<html> We may consider the table bellow as the source of
<title>My Array</title> information to create an array named $Mydata.
<body>
MyData 0 1 2
<?php
$MyData [0][0] = "1"; 0 1 2 3
$MyData [0][1] = "2";
$MyData [0][2] = "3"; 1 4 5 6
$MyData [1][0] = "4";
$MyData [1][1] = "5"; 2 7 8 9
Lines 6-14. Values have assigned to
$MyData [1][2] = "6"; the array.
$MyData [2][0] = "7";
$MyData [2][1] = "8"; Line 16. In the response page we will send the value
$MyData [2][1] = "9"; assigned to $MyData [1][2] in the array. The first number
will be the row and the second one the column, so that in our
print $MyData [1][2]; case the response page will show the value "6"
?>
</body>
</html>
It is also possible to define an array with more dimensions as for example $MyData [5][5][5][5][5].
16
Working with Arrays
In the examples above we have defined all the values within the script one by one, but this assignation
may be done in a different way, as it is described in the example bellow:
</pre>
In this example the array has been defined as comma separated element (the first element in the array is
element 0 !). The array command has been used to define the array.
We may want to generate an array from a data in a text. In the example bellow, each word in a text will be
stored in an array (one word in each element of the array), and them the array will be printed out (with
command print_r), and finally word number 5 will be shown:
In this example we have defined the variable $TheText, and whithin this variable we have include several
words separated by spaces.
17
In the next line, we have splitted the variable $TheText into an array named $Thearray.
Split command have been used to brake $TheText and " " (space) has been used as a delimiter to separate
the substrings.
In the response page we have printed the array by using command print_r, and element number 5 has been
printed out.
It may happend to have a string we want to split, but we do not know how many substrings we may get. In
that case we may use command sizeof to discover how many elements are in our array, and them we may
use that value to write them by using a foreach control structure (see example below).
</pre>
18
Selecting values from a array
In the next example we will count number of element in the array containing the word "o". Two methods
will be used
?> Method 2:
<b>Method 1</b>: Number of
Number of strings containing "o" (case sensitive) strings
<? containing "o"
$counter=0; (case
foreach ($MyArray as $key =>$val){ sensitive)
3
if (substr_count ($val,"o")>0){$counter++;}
Find strings
}
containing "o"
print $counter;
(case
?>
insensitive)
4
Number of strings containing "o" (case insensitive)
<?
$counter=0;
foreach ($MyArray as $key =>$val){
if (substr_count ($val,"o")>0 or substr_count($val,"O")>0){$counter++;}
}
print $counter;
?>
<b>Method 2</b>:
Number of strings containing "o" (case sensitive)
<?
$MyNewArray=preg_grep ("/(o)/",$MyArray);
print sizeof($MyNewArray);
?>
</pre>
19
In the first method, we check all elements in the array (by using foreach control structure), and in each
element we will count number of times the letter "o" is present ( by using command substr_count and a
variable named $counter). At the end of the process $counter is printed out.
In the second method a new array is created from $MyArray by using a preg_grep command. This
command will extract to the new array ($MyNewArray) the elements contained in array the original array
by using a pattern. Learning about pattern syntax is very important for mediu and advances programers.
Here, we just want to let the visitor know this concept. The second method will print the size of the newly
created array, which is the number of elements containing the letter "o" within array $MyArray.
Peter,student,Chicago,123
John,teacher,London,234
Sue,Manager,Sidney,789
And finaly we conected the three lines by separeting the values with "/":
Peter,student,Chicago,123/John,teacher,London,234/Sue,Manager,Sidney,789
The string obtained was saved to a variable named $Mydata in the script bellow. The resulting page will
show a table similar to the original one. This script is not limited by number of rows or columns (the
maximun amount of then is calculate each time we run the script), so we may change information stored in
variable $Mydata, and a table with correct dimensions will be created.
Createatable.php
<?
$Mydata="Peter,student,Chicago,123/John,teacher,London,234/Sue,Manager,Sidney,789";
Createtable($Mydata);
function CreateTable($Mydata){
$MyRows=split ("/", $Mydata);
$NumberRows=sizeof($MyRows);
20
// data contained in each element at array $myRows
// is printed to one line of the table
foreach ($MyRows as $row){
$datainrow=split (",", $row);
print "<tr>"; // start printing a row
foreach ($datainrow as $val){
print "<td>$val</td>"; // print data in the row
}
print "</tr>"; // end printing the row
}
print "</table>"; // end printing out the table
}
?>
This script may be used for several porpouses: we may generate $Mydata by filtering values from an array
as shown bellow:
<?
$query="Chicago";
$Mydata=="";
foreach ($Myclients as $val){
if (substr_count ($val,$query)>0){$Mydata.=$val."/";}
}
Createtable($Mydata);
?>
This code in combination with Createtable() function in the previus example will display only the clients
from Chicago. The $query variable may be obtained from a form.
21
Simple keyword search
In this example, in our first visit a form asking for a keyword will be display. After submitting the
keyword Redirect() function will be activated.
In function Redirect we have create an array named $Websites. This array contains the url of websites and
a its short description. In case the query string is included in the description of the site, the visitor will be
redirected to the corresponding URL.
search.php
<?
if ($_POST){ // check whether info has been posted
$query=$_POST["query"];
Redirect($query);
function Redirect($query){
22