HTML Material
HTML Material
1
HTML
HTML (Hyper Text Markup Language)
is a markup language (markup -instructions for layout and style)
is used to tell a Web browser
where the heading is for a Web page,
what is a paragraph,
What is part of a table and so on, so it can structure
your document and render it properly.
is not programming
Syntax:
2
Simpl
e page
<html>
<head>
<title> GuZo Ethiopia Travel and Tour PLC : About us </title>
</head>
<body>
<h1>About Guzo Ethiopia Travel and Tour PLC</h1>
<p>GuZo Ethiopia Travel and Tour PLC have been serving in
Ethiopia for the last three decades with honesty, great hospitality and
professional ethics. <p>
</body>
</html>
3
Looking at the code
<html>
<head>
<title> GuZo Ethiopia Travel
and Tour PLC : About us </title>
</head>
<body>
<h1>About Guzo Ethiopia
Travel and Tour PLC</h1>
<p>GuZo Ethiopia Travel and
Tour PLC have been serving in Ethiopia
for the last three decades with honesty,
great hospitality and professional ethics. 4
<p>
</body>
5
6
7
<body> . . . </body>
the body of the page, main
content
the information seen in the main
browser window
8
9
PART TWO
10
CHAPTER ONE
BASICS OF PHP
What You Should Already Know: Before you continue you should have a basic understanding
of the following:
HTML/XHTML
CSS
JavaScript
1. INTRODUCTION TO PHP
PHP is a powerful server-side scripting language for creating dynamic and interactive
[Link] is the widely-used, free, and efficient alternative to competitors such as
Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded
directly into the HTML code.
The PHP syntax is very similar to Perl and C. PHP is often used together with Apache (web
server) on various operating systems. It also supports ISAPI and can be used with Microsoft's
IIS on Windows.
2. WHAT IS PHP?
The World Wide Web has changed very fast in so many ways. Sometimes it seems like
yesterday that a little known markup language with a strange name HTML (Hyper Text Markup
Language) was used by some physicists to link scientific documents at a group of CERN servers.
It was wondrous to read some text somewhere in the world with just a simple program, and what
is more information in the document could magically transport you to another one with related
information.
And this spread relatively quickly to other sciences. Text -only interfaces were the norm, and
simplicity of accessing information content the most important part of the equation. Text
documents with a small set of tags and a simple server setup was all you needed to inform your
colleagues and share the knowledge, independently of whether the organic chemist at the other
end was using his trusty Mac, or the theoretician was using her Unix box, or the impoverished
graduate was using a second or third hand PC running very flaky TCP/IP software.
11
Nowadays we expect more, much more than this. We expect a web site with lots of information,
and a good presentation, but we do not want to be distracted by a difficult interface. The
information should be easy to find, and it should be current. A clean and dynamic web site is a
great asset for the user and for the information provider. Long gone (fortunately) are the days of
garish -looking web sites with binky thingies, lots of animated images that usually were hiding a
shallow content depth. We want information, we want it 5 minutes ago and we want it in the
way we like it.
A modern web site is not just a web server; it also includes a way of storing data and querying
(a SQL database perhaps), a way of processing the requests from the user and creating
documents with the appropriate information. Many are the options open to the web developer,
but not all of them as open and general as others. We should not only consider the immediate
task at hand of creating a site with dynamic content, we need to be sure that we can still be
providing the said content independently of the changes in hardware or software technology.
We want to try and insure ourselves against future technology changes, dramatically reduce our
license costs, keep our hardware budget under control, and yet are portable to different web
servers and operating systems. We also want some assurance that we can do something about
that killer bug we just think we found in our web server or scripting environment, be able to
understand (if we want to)how the scripting works, and be able to modify the behavior of our
web server or scripting host to meet some particularly unusual need. Open source products will
be your best assurance that your application that works now in the "Super-Turbo Hexium IX"
machine of today, will work in the "Nanotech Cube Aleph" of tomorrow (I am exaggerating just
a wee bit).
12
3. FEATURES OF PHP
PHP (acronym for: PHP Hypertext Preprocessor), is a server-side embedded scripting language.
This means that it works within an HTML document to confer to it the capacity of generating
content on demand. You can convert your site into a web application, not just a collection of
static pages with information that may not get updated quite so often, which may be alright for a
"personal" web site (yes, we all have made such a beast), but not for one that is going to be used
for business or for education.
You may be asking "But, why PHP? There are so many other options like ASP, Cold
Fusion, Perl, Java, Python, even good old shell/awk/sed scripts?", and the answer will be:
simplicity, an almost natural way of using databases and platform independence.
Of course general scripting or programming languages like Perl, Python, etc. have also
platform independence, and are open source. They are great languages, and sometimes
overkill for what you need, like using a concrete mixer to make scrambled eggs. PHP was
designed to work on the web, and in this ambit it excels; connecting and querying a database
is a simple task that can be handled in 2 or 3 lines of code. The PHP scripting engine is well
optimized for the response times needed on web applications; it can even be part of the web
server itself improving the throughput even more.
If it were only a matter of improving the speed of the scripts, then PHP will be one of
many solutions. But there is more to the PHP equation than that. There is the simplicity and
robustness of the language and the scripting engine. There is the connectivity to an ever
increasing number of database servers, the shorter development cycles and the ease
(encouraged by the syntaxes and constructs) of creating modular and reusable components.
You can perform tasks as simple as creating a feedback form that sends an e-mail to the
web maintainer, to a whole database driven document management system (like Midgard,
[Link] to helpdesk or bug tracking systems (like Keystone,
[Link] to a shopping cart application (like
13
FishCartSQL, [Link] to what would be considered "middle-ware"
packages without the need for extra languages or frameworks, and whole libraries for
quick and flexible development (PHPLIB, [Link]
Then there is the support from a widely distributed and cooperative community, with
several source repositories (like PHP Code Exchange, [Link] or Berber's
WeberDev [Link] many sites with tutorials (PHPBuilder,And did I
mention that it is open source?
There’s no more waiting until the next release for a feature to be added or a bug to get fixed.
Just take the source, make your modifications and there you are, instant customization and
complete control. No more guessing at whether a particular function or feature is insecure, the
code does not lie.
And who knows, maybe your modification gets to be so popular that others may want to use
it (hey! instant fame). And you cannot beat the total price for a development environment
using the combination of Linux, Apache, MySQL and PHP, not only cheaper than other more
proprietary environments, but also more stable and robust.
A PHP file may contain text, HTML tags and scripts. Scripts in a PHP file are executed
on the server.
14
4. WHERE TO START?
To get access to a web server with PHP support, you can:
Install Apache (or IIS) on your own server, install PHP, and MySQL
Or find a web hosting plan with PHP and MySQL support
However, if your server does not support PHP, you must install PHP. Below is a link to a good
Lecture from [Link] on how to install PHP5: [Link]
DOWNLOAD PHP
Download PHP for free here: [Link]
[Link]
15
Download Apache for free here: [Link]
Step 1: In the XAMPP control panel, click on ‘Start’ under ‘Actions’ for the Apache
module. This instructs XAMPP to start the Apache web server.
Step 2: Open your web browser and type in: [Link] or [Link]
Step 4: You should see the following screen. This means you’ve successfully installed
XAMPP on your computer.
Step 5: We will now test whether XAMPP has installed PHP successfully. To do this,
fire up Notepad and type the following into a new document:
16
<?php
?>
Save this file as ‘[Link]’ in c:\xampp\htdocs\ (or whichever directory you installed
XAMPP in).
Step 6: Navigate to localhost/[Link]. You should see the “Hello World” message:
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with <? and end with ?
>.
However, for maximum compatibility, we recommend that you use the standard form (<?
php) rather than the shorthand form.
<?php
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish
one set of instructions from another.
There are two basic statements to output text with PHP: echo and print. Echo () and print() are
language constructs in PHP, both are used to output strings. The speed of both statements is
almost the same. Echo () can take multiple expressions where as print cannot take multiple
expressions. In the example above we have used the echo statement to output the text "Hello World".
17
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.
A PHP file normally contains HTML tags, just like an HTML file, and some PHP
scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the
browser:
There are two basic statements to output text with PHP: echo and print. In the example above
we have used the echo statement to output the text "Hello World".
<html>
<body>
<?php
echo "Hello World"; ?>
</body></html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is
used to distinguish one set of instructions from another.
7. COMMENTS IN PHP
In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
<html>
<body>
<?php
//This is a comment
/*This is a comment block
*/
?>
</body>
</html>
18
SUMMARY:
What is PHP?
PHP stands for PHP: Hypertext Preprocessor
PHP is a server-side scripting language, like ASP (Active Server Page)
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
PHP is an open source software
PHP is free to download and use
PHP is a server-side scripting language.
Why PHP?
19
CHAPTER TWO
PHP VARIABLES
1. VARIABLES: Variables are used for storing values, such as numbers, strings or
function results, so that they can be used many times in a script.
Variables in PHP
Variables are used for storing a value, like text strings, numbers or arrays. When a variable is
set it can be used over and over again in your script. All variables in PHP start with a $ sign
symbol. The correct way of setting a variable in PHP:
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it
will not [Link]'s try creating a variable with a string, and a variable with a number:
<?php
$number = 16;
?>
In a strongly typed programming language, you have to declare (define) the type and name of the
variable before using [Link] PHP the variable is declared automatically when you use it.
20
should be separated with underscore ($my_string), or with capitalization ($myString)
2. PHP String
A string variable is used to store and manipulate a piece of text.
Strings in PHP
String variables are used for a value that contains character [Link] this Lecture we are
going to look at some of the most common functions and operators used to manipulate strings in
PHP. After we create a string we can manipulate it. A string can be used directly in a function or
it can be stored in a variable.
Below, the PHP script assigns the string "Hello World" to a string variable called $txt:
<?php
?>
Hello World
Now, lets try to use some different functions and operators to manipulate our string.
The string functions are part of the PHP core. There is no installation needed to use these
functions.
<?php
21
echo strlen("Hello world!");
?>
12
The length of a string is often used in loops or other functions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the
string)
6
As you see the position of the string "world" in our string is position 6. The reason that it is 6,
and not 7, is that the first position in the string is 0, and not 1.
3. PHP OPERATORS
Operators are used to operate on values. This section lists the different operators used in PHP.
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
10%8 2
10%2 0
x++
x--
Assignment Operators
23
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
Comparison Operators
Logical Operators
Operator Description Example
y=3
|| or x=6
y=3
! not x=6
y=3
24
!(x==y) returns true
25
4. CONTROL STRUCTURES
I. SELECTIVE STATEMENTS
if (condition)
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
<html>
<body>
26
<?php $d=date("D"); if ($d=="Fri")
echo "Have a nice weekend!"; else
echo "Have a nice day!";
?>
</body>
</html>
If more than one line should be executed if a condition is true/false, the lines should be enclosed
within curly braces:
<html>
<body>
<?php $d=date("D"); if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!"; echo "See you on Monday!";
}
?>
</body>
</html>
Syntax
if (condition)
27
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
<html>
<body>
<?php $d=date("D"); if ($d=="Fri")
echo "Have a nice weekend!"; elseif ($d=="Sun")
echo "Have a nice Sunday!"; else
If you want to select one of many blocks of code to be executed, use the Switch statement. The
switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
28
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;
}
Example
This is how it works:
A single expression (most often a variable) is evaluated once
The value of the expression is compared with the values for each case in the structure
If there is a match, the code associated with that case is executed
After a code is executed, break is used to stop the code from running into the next case
The default statement is used if none of the cases are true
<html>
<body>
<?php 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";
}
?>
29
</body>
</html>
30
$i++;
}
?>
</body>
</html>
Syntax
do
{
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 5:
<html>
<body>
<?php
$i=0;
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
31
?>
</body>
</html>
32
6. PHP ARRAYS REFERENCES
An array can store one or more values in a single variable name.
When working with PHP, sooner or later, you might want to create many similar variables.
Instead of having many similar variables, you can store the data as elements in an array. Each
element in the array has its own ID so that it can be easily accessed.
Numeric Arrays
Example 1
In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");
Example 2
In this example we assign the ID key manually:
$names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";
The ID keys can be used in a script:
<?php
33
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?>
The code above will output:
Quagmire and Joe are Peter's neighbors
Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to
do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
In this example we use an array to assign ages to the different persons:
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
Syntax
35
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</body>
</html>
36
CHAPTER THREE
Function is a set of computer codes executed when that code is called. The main concept is how
to create your own functions. For a reference and examples of the built-in functions, please visit
our PHP Reference.
Name the function - It should be possible to understand what the function does by its name.
The name can start with a letter or underscore (not a number)
Add a "{" - The function code starts after the opening curly brace
Example
<html>
<body>
<?php
37
function writeMyName()
writeMyName();
?>
</body>
</html>
<html>
<body>
<?php
function writeMyName()
</body>
38
</html>
Hello world!
Our first function (writeMyName()) is a very simple function. It only writes a static string.
To add more functionality to a function, we can add parameters. A parameter is just like a
variable.
You may have noticed the parentheses after the function name, like: writeMyName(). The
parameters are specified inside the parentheses.
Example 1
The following example will write different first names, but the same last name:
<html>
<body>
<?php
function writeMyName($fname)
39
writeMyName("Hege");
?>
</body>
</html>
Example 2
<html>
<body>
<?php
function writeMyName($fname,$punctuation)
40
echo "My name is ";
writeMyName("Ståle","...");
?>
</body>
</html>
Example
<html>
<body>
<?php
function add($x,$y)
$total = $x + $y;
return $total;
?>
41
</body>
</html>
1 + 16 = 17
Server Side Includes (SSI) are used to create functions, headers, footers, or elements that will
be reused on multiple pages.
You can insert the content of a file into a PHP file before the server executes it, with the
include() or require() function. The two functions are identical in every way, except how they
handle errors. The include() function generates a warning (but the script will continue execution)
while the require() function generates a fatal error (and the script execution will stop after the
error).
These two functions are used to create functions, headers, footers, or elements that can be
reused on multiple pages.
This can save the developer a considerable amount of time. This means that you can
create a standard header or menu file that you want all your web pages to include. When the
header needs to be updated, you can only update this one include file, or when you add a new
page to your site, you can simply change the menu file (instead of updating the links on all web
pages).
42
The include() function takes all the text in a specified file and copies it into the file that uses
the include function.
Example 1
Assume that you have a standard header file, called "[Link]". To include the header file
in a page, use the include() function, like this:
<html>
<body>
<p>Some text</p>
</body>
</html>
Example 2
Now, let's assume we have a standard menu file that should be used on all pages (include
files usually have a ".php" extension). Look at the "[Link]" file below:
<html>
<body>
href="[Link] Us</a>
The three files, "[Link]", "[Link]", and "[Link]" should all include the
43
<?php include("[Link]"); ?>
<p>Some text</p>
</body>
</html>
If you look at the source code of the "[Link]" in a browser, it will look something like
this:<html>
<body>
<a href="[Link]">Home</a>
<p>Some text</p>
</body>
</html>
And, of course, we would have to do the same thing for "[Link]" and "[Link]". By
using include files, you simply have to update the text in the "[Link]" file if you decide to
rename or change the order of the links or add another web page to the site.
The require() function is identical to include(), they only handle errors differently. The include
() function generates a warning (but the script will continue execution) while the require ()
function generates a fatal error (and the script execution will stop after the error).
If you include a file with the include() function and an error occurs, you might get an error
44
message like the one below.
PHP code:
<html>
<body>
<?php
include("[Link]");
?>
</body>
</html>
Error message:
Hello World!
Notice that the echo statement is still executed! This is because a Warning does not stop the
script execution.
Now, let's run the same example with the require() function.
45
PHP code:
<html>
<body>
<?php
require("[Link]");
echo "Hello World!";
?>
</body>
</html>
Error message:
in C:\home\website\[Link] on line 5
The echo statement was not executed because the script execution stopped after the fatal error.
It is recommended to use the require() function instead of include(), because scripts should
not continue executing if files are missing or misnamed.
The PHP date() function is used to format a time or a date. The PHP date() function formats a
timestamp to a more readable date and time.
46
Syntax
date(format,timestamp)
Parameter Description
Optional.
timestampSpecifies a timestamp. Default is the current date and time (as a
timestamp)
A timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT. This is also
known as the Unix Timestamp.
The first parameter in the date () function specifies how to format the date/time. It uses letters
to represent date and time formats. Here are some of the letters that can be used:
An overview of all the letters that can be used in the format parameter can be found in our
PHP Date reference.
Other characters, like"/", ".", or "-" can also be inserted between the letters to add
additional formatting:
47
<?php
date_default_timezone_set('UTC');
echo date("Y/m/d");
echo date("Y.m.d");
echo date("Y-m-d");
?>
2006/07/11
2006.07.11
2006-07-11
The second parameter in the date() function specifies a timestamp. This parameter is optional.
In our next example we will use the mktime() function to create a timestamp for tomorrow.
The mktime() function returns the Unix timestamp for a specified date.
48
Syntax
mktime(hour,minute,second,month,day,year,is_dst)
To go one day in the future we simply add one to the day argument of mktime():
<?php
date_default_timezone_set('UTC');
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
?>
Tomorrow is 2006/07/12
49
CHAPTER FOUR
The PHP $_GET and $_POST variables are used to retrieve information from forms,
like user input.
PHP Form Handling: 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.
For example:
<html>
<body>
<form action="[Link]" 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 "[Link]" file.
<html>
<body>
</body>
</html>
50
A sample output of the above script may be:
Welcome John.
Form Validation
User input should be validated whenever possible. Client side validation is faster, and will
reduce server load.
However, any site that gets enough traffic to worry about server resources may also need to
worry about site security. You should always use server side validation if the form accesses a
database.
A good way to validate a form on the server is to post the form to itself, instead of jumping to a
different page. The user will then get the error messages on the same page as the form. This
makes it easier to discover the error.
PHP $_GET: The $_GET variable is used to collect values from a form with method="get".
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).
Example
</form>
51
When the user clicks the "Submit" button, the URL sent could look something like this:
[Link]
<?name=Peter&age=37
The "[Link]" 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):
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.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.
Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to send.
The limitation is about 2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.
52
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
PHP $_POST
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 method is invisible to others and has no limits on the amount
of information to send.
Example
</form>
When the user clicks the "Submit" button, the URL will not contain any form data, and will
look something like this:
[Link]
The "[Link]" 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):
53
Welcome <?php echo $_POST["name"]; ?>.<br />
Variables sent with HTTP POST are not shown in the URL
However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.
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
<html>
<body>
54
<label for="file">Filename:</label>
</form>
</body>
</html>
The enctype attribute of the <form> tag specifies which content-type to use when
submitting the form. "multipart/form-data" is used when a form requires binary data,
like the contents of a file, to be uploaded
The type="file" attribute of the <input> tag specifies that the input should be processed as
a file. For example, when viewed in a browser, there will be a browse-button next to the
input field.
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform
file uploads.
<?php
if ($_FILES["file"]["error"] > 0)
else
55
{
?>
By using the global PHP $_FILES array you can upload files from a client computer to the
remote server.
The first parameter is the form's input name and the second index can be either "name",
"type", "size", "tmp_name" or "error".
Like this:
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the
server
This is a very simple way of uploading files. For security reasons, you should add restrictions
on what the user is allowed to upload.
Restrictions on Upload
In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg
files and the file size must be under 20 kb:
<?php
56
($_FILES["file"]["size"] < 20000))
if ($_FILES["file"]["error"] > 0)
else
else
?>
The examples above create a temporary copy of the uploaded files in the PHP temp folder on
the server.
The temporary copied files disappear when the script ends. To store the uploaded file we need
to copy it to a different location:
57
<? Php
if ($_FILES["file"]["error"] > 0)
else
if (file_exists("upload/" . $_FILES["file"]["name"]))
else
move_uploaded_file($_FILES["file"]
["tmp_name"], "upload/" . $_FILES["file"]
["name"]);
58
}}}
else
}?>
The script above checks if the file already exists, if it does not, it copies the file to
the specified folder i.e. this example saves the file to a new folder called "upload".
59
CHAPTER FIVE
A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will
send the cookie too. With PHP, you can both create and retrieve cookie values.
Note: The setcookie() function must appear BEFORE the <html> tag.
Example
In the example below, we will create a cookie named "user" and assign the value "Alex Porter"
to it. We also specify that the cookie should expire after one hour:
<html>
<body>
<?php
Some code;
?>
</body>
</html>
60
Note: The value of the cookie is automatically URL encoded when sending the cookie, and
automatically decoded when received (to prevent URL encoding, use setrawcookie() instead).
In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie has been set:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
else
?>
</body>
</html>
61
62
C. . How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
<?php
?>
If your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. One method is to pass
the data through forms (forms and user input are described earlier in this Lecture).
The form below passes the user input to "[Link]" when the user clicks on the "Submit"
button:
<html>
<body>
</form>
</body>
</html>
63
Retrieve the values in the "[Link]" file like this:
<html>
<body>
</body>
</html>
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.
64
B. CREATE, USE AND DELETE SESSION
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>
<?php
Some code;
?>
</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.
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
65
<html>
<body>
<?php
echo "Pageviews=".
$_SESSION['views']; ?>
</body>
</html>
Output:
Pageviews=1
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;
66
Destroying a Session
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();
?>
67
CHAPTER SIX
PHP DATA BASE MANIPULATIONS
6.1. INTRODUCTION
MySQL is the most popular open source database server.
Download MySQL Database
If you don't have a PHP server with a MySQL Database, you can download
MySQL for free here: [Link]
Facts About MySQL Database
One great thing about MySQL is that it can be scaled down to support embedded
database applications. Perhaps it is because of this reputation that many people
believe that MySQL can only handle small to medium-sized systems.
The truth is that MySQL is the de-facto standard database for web sites that
support huge volumes of both data and end users (like Fraudster, Yahoo, Google).
Look at [Link] for an overview of companies that
use MySQL.
What is MySQL?
MySQL is a database. A database defines a structure for storing information. In a
database, there are tables. Just like HTML tables, database tables contain rows,
columns, and cells. Databases are useful when storing information categorically. A
company may have a database with the following tables: "Employees", "Products",
"Customers" and "Orders".
Database Tables
A database most often contains one or more tables. Each table has a name (e.g.
"Customers" or "Orders"). Each table contains records (rows) with data.
Below is an example of a table called "Persons":
68
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
The table above contains three records (one for each person) and four
columns (LastName, FirstName, Address, and City).
Syntax
mysql_connect(servername,username,password);
Parameter Description
Optional. Specifies the server to connect to. Default value is
servername "localhost:3306"
Optional. Specifies the username to log in with. Default value
username is the name of the
user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Note: There are more available parameters, but the ones listed above are the most
69
important. Visit our full PHP MySQL Reference for more details.
Example
In the following example we store the connection in a variable ($con) for later use
in the script. The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123"); if
(!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code ?>
CLOSING A CONNECTION
The connection will be closed as soon as the script ends. To close the
connection before, use the mysql_close() function.
<?php
$con = mysql_connect("localhost","peter","abc123"); if
(!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
6.3. QUERIES
A query is a question or a request. With MySQL, we can query a database for
specific information and have a recordset returned. Look at the following query:
70
SELECT LastName FROM Persons;
The query above selects all the data in the LastName column in the Persons table,
and will return a recordset like this:
LastName
Hansen
Svendson
Pettersen
Example
In the following example we create a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!
$con)
{
71
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con); ?>
Create a Table
The CREATE TABLE statement is used to create a database table in MySQL.
Syntax
CREATE TABLE table_name
(column_name1 data_type, column_name2 data_type, column_name3 data_type,
....... )
72
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
73
digits can be
smallint(size) specified in the size parameter
tinyint(size)
mediumint(size)
bigint(size)
Hold numbers with fractions. The maximum
decimal(size,d) number of
digits can be specified in the size parameter.
double(size,d) The maximum
number of digits to the right of the decimal is
float(size,d) specified in
the d parameter
74
characters
Holds a variable string with a maximum
Text length of 65535
Blob characters
Holds a variable string with a maximum
Mediumtext length of 16777215
Mediumblob characters
Holds a variable string with a maximum
Longtext length of
Longblob 4294967295 characters
75
have up to 64
list items and can store more than one choice
Example
$sql = "CREATE TABLE person (personID int NOT NULL
AUTO_INCREMENT, PRIMARY KEY(personID), FirstName varchar(15),
LastName varchar(15), Age int )";
mysql_query($sql,$con);
76
The INSERT INTO statement is used to insert new records into a database table.
Insert Data into a Database Table
The INSERT INTO statement is used to add new records to a database table.
Syntax
INSERT INTO table_name VALUES (value1, value2,....)
You can also specify the columns where you want to insert the data:
Note: SQL statements are not case sensitive. INSERT INTO is the same as insert
into.
To get PHP to execute the statements above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
In the previous chapter we created a table named "Person", with three columns;
"Firstname", "Lastname" and "Age". We will use the same table in this example.
The following example adds two new records to the "Person" table:
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!
$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO person (FirstName, LastName, Age) VALUES
77
('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO person (FirstName, LastName,
Age) VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con); ?>
Insert Data From a Form Into a Database
Now we will create an HTML form that can be used to add new records to the
"Person" table.
Here is the HTML form:
<html>
<body>
When a user clicks the submit button in the HTML form in the example above, the
form data is sent to "[Link]". The "[Link]" file connects to a database, and
retrieves the values from the form with the PHP $_POST variables. Then, the
mysql_query() function executes the INSERT INTO statement, and a new record
will be added to the database table.
78
Below is the code in the "[Link]" page:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
79
Syntax
SELECT column_name(s) FROM table_name
Note: SQL statements are not case sensitive. SELECT is the same as select. To get
PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example selects all the data stored in the "Person" table (The *
character selects all of the data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
The example above stores the data returned by the mysql_query() function in the
$result variable. Next, we use the mysql_fetch_array() function to return the first
80
row from the record set as an array. Each subsequent call to mysql_fetch_array()
returns the next row in the record set. The while loop loops through all the records
in the recordset. To print the value of each row, we use the PHP $row variable
($row['FirstName'] and $row['LastName']).
Peter Griffin
Glenn Quagmire
Firstname Lastname
Quagmi
Glenn re
Peter Griffin
82
The following operators can be used with the WHERE clause:
Operator Description
= Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Note: SQL statements are not case sensitive. WHERE is the same as where.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
The following example will select all rows from the "Person" table, where
FirstName='Peter':
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM
83
person WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
The output of the code above will be:
Peter Griffin
84
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person ORDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con); ?>
The output of the code above will be:
Glenn Quagmire 33
Peter Griffin 35
Syntax
UPDATE table_name SET column_name = new_value WHERE column_name =
some_value;
Note: SQL statements are not case sensitive. UPDATE is the same as update.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
Earlier in the Lecture we created a table named "Person". Here is how it looks:
86
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Person SET Age = '36' WHERE FirstName = 'Peter'
AND LastName = 'Griffin'"); mysql_close($con);
?>
After the update, the "Person" table will look like this:
FirstName LastName Age
Peter Griffin 36
Glenn Quagmire 33
PHP MySQL Delete From
The DELETE FROM statement is used to delete rows from a database table.
Delete Data In a Database
The DELETE FROM statement is used to delete records from a database table.
Syntax
DELETE FROM table_name WHERE column_name = some_value
Note: SQL statements are not case sensitive. DELETE FROM is the same as
delete from.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
Earlier in the Lecture we created a table named "Person". Here is how it looks:
FirstName LastName Age
87
Peter Griffin 35
Glenn Quagmire 33
The following example deletes all the records in the "Person" table where
LastName='Griffin':
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("DELETE FROM Person WHERE
LastName='Griffin'"); mysql_close($con);
?>
After the deletion, the table will look like this:
88
SUMMARIZED NOTE AND LAB MANUAL
The data in MYSQL is stored in database object called tables. A table is a collection of related
data entries and it consists of columns and rows. Databases are useful when storing information
categorically. A company may have a database.
We can manage our MYSQL database server using a management tool called phpmyadmin. This
tool helps us to create our database and manage our database simply.
Now let us see how we interact with our MYSQL database using our php script. There are four
steps involved that we have to follow in order to talk to database, and they are listed as follows:
To connect to the MYSQL database server we need to use the mysql_connect () function. This
takes the following parameters:
To select a database we use php built-in function mysql_select (). This function takes two
parameters:
To execute queries we use yet another built –in PHP function called mysql_query (). This
function takes a query as a parameter and returns a result set.
4. Close connection :-
89
Since leaving the connection open when we are not using the database leads to security
issues, we need to close the connection after we are done using it by the function:
mysql_close ($connection);
Now let us look at an example that demonstrates the above definitions. We will assume we
have database server at localhost with user name root and password and we have a database
called WKU and this database has table called users and have two attributes username and
password.
90
define("DB_PASS" ," ");
define("DB_NAME" ,"WKU");
//1. create database connection
$connnection=mysql_connect("DB_SERVER","DB_USER","DB_PASS");
if (!$connection)
{
die("Database connection failed: " . mysql_error());
}
//2. select a database to use
$db_select = mysql_connect_db("DB_NAME",$connection);
if (!db_select)
{
die('database selection failed: ' . mysql_error());
}
91
[Link]
<?php
//creating connection to database
$conn=mysql_connect("localhost","root","");
//selecting the database wku
mysql_select_db("wku",$conn);
//database query to retrieve all IDs form student table
$q1="select ID from student";
//query the database and assign it to variable result
$res=mysql_query($q1,$conn);
//creating a search form
echo"<form action='".$_SERVER['PHP_SELF']."' method=\"post\">";
echo"<select name=\"sel\">";
//fetching the result
while($row=mysql_fetch_row($res))
{
echo "<option value=\"$row[0]\">".$row[0]."</option>";
}
//closing the form and select tag
echo"</select>";
echo"<input type='submit' name='search' value='search'>
</form>";
//creating a check for wheather we click search or not
if(isset($_POST['search']))
{
//recieving value form select drop down option using POST
$id=$_POST['sel'];
//query for retrieving all values that match the ID that we choose from the dropdown
$q2="select * from students where ID='$id'";
$res2=mysql_query($q2,$conn);
92
//creating a form for Insert and delete
echo"<form action='".$_SERVER['PHP_SELF']."'method=\"post\">";
//retrieving and displaying all values using textbox
while($row1=mysql_fetch_array($res2))
{
echo" Student ID <input type='text' name='ID' value='".$row1['ID']."'> <br>";
echo"First Name:<input type='text' name='fname' value='".$row1['fName']."'>";
echo"</br>Last Name:<input type='text' name='Lname' value='".$row1['Lname']."'>";
echo"</br>Dep :<input type='text' name='dep' value='".$row1['dep']."'>";
}
echo"<br> <input type='submit' name='Insert' value='Insert'>
<input type='submit' name='delete' value='Delete'></form>";
}
//check
if(isset($_POST['Insert']))
{
$id=$_POST['ID'];
$fname=$_POST['fname'];
$lname=$_POST['Lname'];
$dep=$_POST['dep'];
//query statment for Insert
$q3="Insert into students values('$fname','$lname','$dep','$id')";
$res3=mysql_query($q3,$conn);
if(!$res3)
die("query error ".mysql_error());
echo"you query successfully!!!!";
}
if(isset($_POST['delete']))
{
$id=$_POST['ID'];
93
$name=$_POST['fname'];
//query statment for delete
$q4="delete from students where ID='$id'";
$res4=mysql_query($q4,$conn);
if(!$res4) die("query error ".mysql_error());
echo"you have erased user".$fname." !!!!";
}
?>
[Link]
<?php
//creating connection to database
$conn=mysql_connect("localhost","root","");
//selecting the database wku
mysql_select_db("wku",$conn);
//database query to retrieve all IDs form student table
$q1="select ID from student";
//query the database and assign it to variable result
$res=mysql_query($q1,$conn);
//creating a search form
echo"<form action='".$_SERVER['PHP_SELF']."' method=\"post\">";
echo"<select name=\"sel\">";
//fetching the result
while($row=mysql_fetch_row($res))
{
echo "<option value=\"$row[0]\">".$row[0]."</option>";
}
//closing the form and select tag
echo"</select>";
94
echo"<input type='submit' name='search' value='search'></form>";
//creating a check for wheather we click search or not
if(isset($_POST['search']))
{
//recieving value form select drop down option using POST
$id=$_POST['sel'];
//query for retrieving all values
//that match the ID that we choose from the dropdown
$q2="select * from students where ID='$id'";
$res2=mysql_query($q2,$conn);
//creating a form for update and delete
echo"<form action='".$_SERVER['PHP_SELF']."'method=\"post\">";
//retrieving and displaying all values using textbox
while($row1=mysql_fetch_array($res2))
{
echo"<input type='hidden' name='ID' value='".$row1['ID']."'>";
echo"First Name:<input type='text' name='fname' value='".$row1['fName']."'>";
echo"</br>Last Name:<input type='text' name='Lname' value='".$row1['Lname']."'>";
echo"</br>Dep :<input type='text' name='dep' value='".$row1['dep']."'>";
}
echo"</br>Click to update:<input type='submit' name='update' value='update'>
</br>click to Delete:<input type='submit' name='delete' value='Delete'></form>";
}
//check
if(isset($_POST['update']))
{
$id=$_POST['ID'];
$fname=$_POST['fname'];
$lname=$_POST['Lname'];
$depid=$_POST['dep'];
95
//query statment for update
$q3="update students set fName='$fname',Lname='$lname',dep='$dep' where ID='$id'";
$res3=mysql_query($q3,$conn);
if(!$res3)
die("query error ".mysql_error());
echo"you updated successfully!!!!";
}
if(isset($_POST['delete']))
{
$id=$_POST['ID'];
$name=$_POST['fname'];
//query statment for delete
$q4="delete from students where ID='$id'";
$res4=mysql_query($q4,$conn);
if(!$res4)
die("query error ".mysql_error());
echo"you have erased user".$fname." !!!!";
}
?>
96
ACTIVITY
1. Create a table named Borrowed_Books under the ‘wku’ database with attributes
Student_ID, Book_ID, Book_Title, Author, Publisher and Borrowed_date. The Student_ID in
this table is a foreign key which refers to the ID in student table. (assume one book is
borrowed by one student, but 1 student can borrow many books)
2. Create a form that inserts all the borrowed books to this table(insert at least 6 records).
Student_ID should be inserted in the Address table only if it does exist in the Student table.
3. Create a script that retrieves all the students that borrowed books and another one which
retrieves only male students that borrowed books.
4. Create another script that retrieves all students that borrowed more than one books.
97