0% found this document useful (0 votes)
29 views52 pages

Advanced Internet Programming Notes

The document is a lecture note on Advanced Internet Programming, focusing on server-side scripting with PHP. It covers topics such as PHP syntax, variables, form creation, file handling, and database interaction using MySQL. The material is designed for students at Infolink University College, providing a comprehensive overview of PHP and its applications in web development.

Uploaded by

bayelignalemu858
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views52 pages

Advanced Internet Programming Notes

The document is a lecture note on Advanced Internet Programming, focusing on server-side scripting with PHP. It covers topics such as PHP syntax, variables, form creation, file handling, and database interaction using MySQL. The material is designed for students at Infolink University College, providing a comprehensive overview of PHP and its applications in web development.

Uploaded by

bayelignalemu858
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lecture Note: Advanced internet programming 2015 E.

INFOLINK UNIVERSITY COLLEGE

DILLA CAMPUS

DEPARTMENT OF INFORMATION TECHNOLOGY

Advanced Internet Programming Module

Amanuel Tadiwos

(MSc in Computer Science)

Dilla, Ethiopia

Nov, 2022

Prepared by Amanuel Tadiwos Page 1


Lecture Note: Advanced internet programming 2015 E.C

Contents
Chapter 1: - Server Side Scripting Basics in PHP ......................................................................................... 3
1.1 Overview of Client Side Script ........................................................................................................... 3
1.2. Introduction to Server Side Script ...................................................................................................... 3
1.3. PHP Basic Syntax .............................................................................................................................. 5
1.4. Variables and Constants ..................................................................................................................... 9
1.5. PHP Operators (Reading Assignment) ............................................................................................. 15
1.6. Manipulate Strings ........................................................................................................................... 16
Chapter 2: PHP Statements and Form Creations ........................................................................................ 18
2.1. PHP statements: - Use Conditionals/Decision Making, LOOP, Arrays........................................... 18
2.1.1. Conditionals/Decision Making Statements ............................................................................... 18
2.2PHP GET, POST & REQUIST Methods ........................................................................................... 26
2.3 Creating PHP Forms ..................................................................................................................... 28
2.4 Form Validation ............................................................................................................................ 30
Chapter 3 Files and Directories in PHP ...................................................................................................... 33
3.1. Reading files/ Directories ................................................................................................................. 33
3.2. Upload Files ..................................................................................................................................... 36
3. 3 PHP Cookies and Session ................................................................................................................ 37
3.4 PHP - File Inclusion .......................................................................................................................... 41
Chapter 4:- PHP Database / PHP with MYSQL ......................................................................................... 44
Create MySQL Database Using PHP ...................................................................................................... 46
Creating Database Tables ........................................................................................................................ 47

Prepared by Amanuel Tadiwos Page 2


Lecture Note: Advanced internet programming 2015 E.C

Chapter 1: - Server Side Scripting Basics in PHP

1.1 Overview of Client Side Script


 Client-side scripting generally refers to the class of computer programs on the web that
are executed client-side, by the user's web browser
 Client-side scripts are often embedded within an HTML or XHTML document (hence
known as an "embedded script"), but they may also be contained in a separate file, to which
the document (or documents) that use it make reference (hence known as an "external
script").
 Instructions can be followed without further communication with the server
 By viewing the file that contains the script, users may be able to see its source code. Many
web authors learn how to write client-side scripts partly by examining the source code for
other authors' scripts.
 The client-side environment used to run scripts is usually a browser. The processing takes
place on the end users computer. The source code is transferred from the web server to the
user‘s computer over the internet and run directly in the browser.
 The scripting language needs to be enabled on the client computer. Sometimes if a user is
conscious of security risks they may switch the scripting facility off. When this is the case
a message usually pops up to alert the user when script is attempting to run.
 Includes :-
JavaScript, Action Script (used to create animated interactive web applications for
Adobe Flash Player using Adobe Flash Pro), VBScript (NOTE: VBScript can also
be used as Server-side so that processing is done on the server.), Python, html etc
1.2. Introduction to Server Side Script

Server-side scripting language, which means that the scripts are, executed on the server, the
computer where the Web site is located.

Server-side scripting is a web server technology in which a user's request is fulfilled by running a
script directly on the web server to generate dynamic web pages. It is usually used to provide
interactive web sites that interface to databases or other data stores. This is different from client-
side scripting where scripts are run by the viewing web browser.
Prepared by Amanuel Tadiwos Page 3
Lecture Note: Advanced internet programming 2015 E.C

The primary advantage to server-side scripting is the ability to highly customize the response based
on the user's requirements, access rights, or queries into data stores. From security point of view,
server-side scripts are never visible to the browser as these scripts are executes on the server and
emit HTML corresponding to user's input to the page.

In contrast, server-side scripts, written in languages such as PHP, [Link], Java, ColdFusion,
Perl, Ruby, Go, Python, and server-side JavaScript, are executed by the web server when the user
requests a document. They produce output in a format understandable by web browsers (usually
HTML), which is then sent to the user's computer. The user cannot see the script's source code
(unless the author publishes the code separately), and may not even be aware that a script was
executed. Documents produced by server-side scripts may, in turn, contain client-side scripts.

Server-side Web scripting is mostly about connecting Web sites to back end servers, such as
databases. This enables two-way communication:

• Client to server: Customer-entered information as request.


• Server to client: Web pages can be assembled from back end-server to give
output.

Server-side scripting is about "programming" the behavior of the server while client-side scripting
is about "programming" the behavior of the browser. Normally, when a browser requests an HTML
file, the server returns the file. However, if the file contains a server-side script, the script is
executed on the server before the file is returned to the browser as plain HTML.

A server script can do:-

 Dynamically edit, change or add any content to a Web page


 Respond to user queries or data submitted from HTML forms
 Access any data or databases and return the result to a browser
 Customize a Web page to make it more useful for individual users
 Provide security since server code cannot be viewed from a browser

In server side script, since the scripts are executed on the server, the browser that displays the file
does not need to support scripting at all. The followings are server-side scripts:

Prepared by Amanuel Tadiwos Page 4


Lecture Note: Advanced internet programming 2015 E.C

• PHP (*.php)
• Active Server Pages (ASP)
• ANSI C scripts Java via JavaServer Pages (*.jsp)
• JavaScript using Server-side JavaScript (*.ssjs)
• Lasso (*.lasso) etc

The main focus here is PHP, which is a server-side scripting language, which can be embedded
in HTML or used as a standalone binary, and could be run with open source software like
WAMP server.

 PHP can dynamically create the HTML code that generates the Web page.
 Web page visitors see the output from scripts, but not the scripts themselves.

1.3. PHP Basic Syntax

PHP stands for PHP: Hypertext Preprocessor. It is a server-side scripting language, which can be
embedded in HTML. Over the past few years, PHP and server-side Java have gained momentum,
while ASP has lost mindshare.

PHP is a server-side scripting language, which means that the scripts are executed on the server,
the computer where the Web site is located. This is different than JavaScript, another popular
language for dynamic Web sites. JavaScript is executed by the browser, on the user‘s computer.
Thus, JavaScript is a client-side language.

Because PHP scripts execute on the server, PHP can dynamically create the HTML code that
generates the Web page, which allows individual users to see customized Web pages. Web page
visitors see the output from scripts, but not the scripts themselves.

PHP is particularly strong in its ability to interact with databases. PHP handles connecting to the
database and communicating with it, so we don‘t need to know the technical details for connecting
to a database or for exchanging messages with it, it is enough telling PHP the name of the database
and where it is, and PHP handles the details. It connects to the database, passes our instructions to
the database, and returns the database response to us.

Major databases currently supported by PHP include the following:

Prepared by Amanuel Tadiwos Page 5


Lecture Note: Advanced internet programming 2015 E.C

 dBASE ,Informix ,Ingres, Microsoft SQL Server ,mSQL ,MySQL ,Oracle


,PostgreSQL,Sybase and etc.

Hence, PHP scripts in the Web site can store data in and retrieve data from any
supported database. PHP also can interact with supported databases outside a Web
environment. Database use is one of PHP‘s best features.

Use of PHP:

 PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can
send data, return data to the user.
 Using php, it is possible to add, delete, and modify elements within our database.
 It helps to assign sessions and cookies for privacy.
 Using PHP, we can restrict users to access some pages of the website.
 It can encrypt data and so mores

The syntax of PHP is: - There are four ways to write php syntaxes:-

1. Canonical PHP tags:


 The most universally effective PHP tag style is:
<?php statements written here.. ?>
 This is the common one
2. Short-open (SGML-style) tags: Short or short-open tags look like this:

<? Statements written here…?>


 Short tags are, as one might expect, the shortest option
 We must do one of two things to enable PHP to recognize the tags:
• Choose the --enable-short-tags configuration option when building PHP.
• Set the short_open_tag setting in [Link] file to on. This option must be
disabled to parse XML with PHP because the same syntax is used for XML
tags.

Prepared by Amanuel Tadiwos Page 6


Lecture Note: Advanced internet programming 2015 E.C

3. ASP-style tags: ASP-style tags mimic the tags used by Active Server Pages to delineate
code blocks. ASP-style tags look like this:
<%... %>
 To use ASP-style tags, we should set the configuration option in your [Link] file.
4. HTML script tags: HTML script tags look like this:
<script language= “php”>… </script>

To work with server script, for example with PHP, we need to install a web server, programming
itself, and database server. For PHP, we install PHP as a programming. There are many web servers
to choose for PHP uses; the most commonly used web server is called Apache which we can
download from the internet freely. Similarly, for database, there are many options to use; the most
popular database server for web pages is MySQL which again can be downloaded freely from
internet.

PHP is also available freely on the internet. In order to develop and run PHP Web pages three vital
components need to be installed on computer system.

• Web Server - PHP will work with virtually all Web Server software, including Microsoft's
Internet Information Server (IIS) but then most often used is freely available Apache
Server.
• Database - PHP will work with virtually all database software, including Oracle and
Sybase but most commonly used is freely available MySQL database.
• PHP Parser - In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser.

The official PHP website ([Link]) has installation instructions for


PHP: [Link]

For the apache code to execute properly, it should be saved in web directory. The web directory
depends on what web server is used. For example, for xampp web server, our web directory can
be install in C:\xampp\htdocs‖. Hence, we should save PHP files in this folder, www.

For XAMPP server, we save the php code in C:\xampp\htdocs\your file here.

Prepared by Amanuel Tadiwos Page 7


Lecture Note: Advanced internet programming 2015 E.C

1.4. Writing PHP Comments and Output Statements

A comment is the portion of a program that exists only for the human reader and stripped out
before displaying the programs result. There are two commenting formats in PHP:

 Single-line comments: They are generally used for short explanations or notes relevant
to the local code. Here are the examples of single line comments.
<?php
#This is a single line comment and
// This also a single line comments too. Each style comments only print "An example
with single line comments";
?>
 Multi-lines comments: They are generally used to provide pseudo code algorithms and
more detailed explanations when necessary. Use /* and */ Here are the example of multi
lines comments.
<?php
/* This is a comment with multiline
………………………………………
………………………………………
…………………………………….
*/
Print "An example with multi
line comments";

?>
Output Statements:-

The two most basic constructs for displaying output in PHP are echo and print. Both can be used either
with parentheses or without them.

Echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take
multiple parameters (although such usage is rare) while print can take one argument. echo is marginally
faster than print. The echo or print statement can be used with or without parentheses: echo or echo().

The general format of the echo statement is as follows: echo outputitem1, outputitem2, outputitem3, . . .;
echo (output);

Prepared by Amanuel Tadiwos Page 8


Lecture Note: Advanced internet programming 2015 E.C

The parameterized version of echo does not accept multiple arguments. The general format of the print
statement is as follows:

print output;
print(output);
Example: different ways of echoand print
echo 123; //output: 123
echo “Hello World!”; //output: Hello world!
echo (“Hello World!”); //output: Hello world!
echo “Hello”,”World!”; //output: Hello World!
echo Hello World!; //output: error, string
should be enclosed in quotes
print (“Hello world!”); //output: Hello world!

The command print is very similar to echo, with two important differences:

 Unlike echo, print can accept only one argument.


 Unlike echo, print returns a value, which represents whether the print statement succeeded.

1.5. Variables and Constants


A. PHP Variables

A variable is a special container that can be defined to hold a value such as number, string, object,
array, or a Boolean. The main way to store information in the middle of a PHP program is by using
a variable. Here are the most important things to know about variables in PHP.

 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.

Prepared by Amanuel Tadiwos Page 9


Lecture Note: Advanced internet programming 2015 E.C

For example:- $distance = 2; $name = “stay home”;

As shown above, Numbers are not enclosed in quotes when they are assigned to variable. However,
strings should be enclosed in either single or double quotes (― or ‗). The quotes tell PHP that the
characters are a string, handled by PHP as a unit. Without the quotes, PHP doesn‘t know the
characters are a string and won‘t handle them correctly. PHP has a total of eight data types which
we use to construct our variables:

1. Integers: are whole numbers, without a decimal point, like 4195.


2. Doubles: are floating-point numbers, like 3.14159 or 49.1.
3. Booleans: have only two possible values either true or false.
4. NULL: is a special type that only has one value: NULL. simply assign it like this:
$my_var = NULL; The special constant NULL is capitalized by convention, but actually
it is case insensitive. A variable that has been assigned NULL has the following
properties:
• It evaluates to FALSE in a Boolean context.
• It returns FALSE when tested with IsSet() function.
5. Strings: are sequences of characters, like 'PHP supports string operations.'
6. Arrays: are named and indexed collections of other values.
7. Objects: are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
8. Resources: are special variables that hold references to resources external to PHP (such
as database connections). The first five are simple types, and the next two (arrays and
objects) are compound - the compound types can package up other arbitrary values of
arbitrary type, whereas the simple types cannot.

 Strings:

They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string

$string_1 = "This is a string in double quotes";

$string_0 = ""; // a string with zero characters

Prepared by Amanuel Tadiwos Page 10


Lecture Note: Advanced internet programming 2015 E.C

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.

<?php

$variable = "name";

$literally = 'My $variable will not print!\\n';


echo($literally);
$literally = "My $variable will print!\\n";
echo($literally);
?>

Find output to the above code.

There are no artificial limits on string length - within the bounds of available memory, we ought
to be able to make arbitrarily long strings. Strings that are delimited by double quotes (as in "this")
are preprocessed in both the following two ways by PHP:

 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are:

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

PHP provides a large number of predefined variables to all scripts. The variables represent everything
from external variables to built-in environment variables, last error messages to last retrieved headers.

 Superglobals — Superglobals are built-in variables that are always available in all scopes
 $GLOBALS — References all variables available in global scope

Prepared by Amanuel Tadiwos Page 11


Lecture Note: Advanced internet programming 2015 E.C

 $_SERVER — Server and execution environment information


 $_GET — HTTP GET variables
 $_POST — HTTP POST variables
 $_FILES — HTTP File Upload variables
 $_REQUEST — HTTP Request variables, and can replace $_POST, $_GET and $_COOKIE
variables
 $_SESSION — Session variables
 $_COOKIE — HTTP Cookies
 $php_errormsg — The previous error message
$HTTP_RAW_POST_DATA — Raw POST data
 $http_response_header — HTTP response headers
 $argc — The number of arguments passed to script
 $argv — Array of arguments passed to script

Many of these variables, however, cannot be fully documented as they are dependent upon which
server are running, the version and setup of the server, and other factors.

Removing Variables

• We can uncreated the variable by using this statement: unset (VariableName);


• After this statement, the variable $age no longer exists. If we try to echo it, you get an
undefined variable‖ notice. It is possible to unset more than one variable at once, as
follows:

unset($age, $name, $address);

Variable Scope:

Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of three scope types:

Local variables:- The variable is only accessible from within the function (or method) that created
it A variable declared in a function is considered local; that is, it can be referenced solely in that
function. Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function:

Prepared by Amanuel Tadiwos Page 12


Lecture Note: Advanced internet programming 2015 E.C
<?php

$x = 4;
function assignx () {
$x = 0;
echo "\$x inside function is $x. ";
}
assignx()
;
echo "\$x outside of function is $x. ";
?>
The output will be:-

o $x inside function is 0.
o $x outside of function is 4.

Global variables: - The variable is accessible from anywhere in the script. Global variable can be
accessed in any part of the program. However, in order to be modified, a global variable must be
explicitly declared to be global in the function in which it is to be modified. This is accomplished,
conveniently enough, by placing the keyword GLOBAL in front of the variable that should be
recognized as global. Placing this keyword in front of an already existing variable tells PHP to use
the variable having that name. Consider an example:

<?php

$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++ ; echo
"Somevar is $somevar";
} addit();
?>

The output will be:-

o Somevar is 16

Prepared by Amanuel Tadiwos Page 13


Lecture Note: Advanced internet programming 2015 E.C

Static variables:- this type of variables be either a global or local variable. Both are created by
preceding the variable declaration with the keyword static. In contrast to the variables declared as
function parameters, which are destroyed on the function's exit, a static variable will not lose its
value when the function exits and will still hold that value should the function be called again.

<?php

function keep_track() {

STATIC $count = 0;

$count++;
echo $count; print " ";
}

keep_track();
keep_track();
keep_track();
?>

This will produce following result. 1


2
3
Variable Naming:

Rules for naming a variable are:

• Variable names must begin with a letter or underscore character.


• A variable name can consist of numbers, letters, underscores but you cannot use
characters like +
, - , % , ( , ) . & , etc
• There is no size limit for variables.

B. PHP Constants

A constant is a name or an identifier for a simple value. A constant value cannot change during the
execution of the script. By default a constant is case-sensitive. By convention, constant identifiers
are always uppercase. A constant name starts with a letter or underscore, followed by any number

Prepared by Amanuel Tadiwos Page 14


Lecture Note: Advanced internet programming 2015 E.C

of letters, numbers, or underscores. If we have defined a constant, it can never be changed or


undefined.

To define a constant we have to use define() function and to retrieve the value of a constant. Unlike
with variables, you do not need to have a constant with a $. We can also use the function constant()
to read a constant's value if we wish to obtain the constant's name dynamically.

constant () function is used to return the value of the constant. This is useful when we want to
retrieve value of a constant, but we do not know its name, i.e. It is stored in a variable or returned
by a function. constant () example:

<?php
define("MINSIZE", 50); echo MINSIZE; echo‖<br>‖;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants. PHP provides
a large number of predefined constants to any script which it runs. There are five magical
constants that change depending on where they are used. For example, the value of __LINE__
depends on the line that it's used on in script.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts
with a letter or underscore, followed by any number of letters, numbers, or underscores. As a
regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
1.5. PHP Operators (Reading Assignment)

PHP divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators

Prepared by Amanuel Tadiwos Page 15


Lecture Note: Advanced internet programming 2015 E.C

The ternary operator

One especially useful construct is the ternary conditional operator, which plays a role somewhere
between a Boolean operator and a true branching construct. Its job is to take three expressions and
use the truth value of the first expression to decide which of the other two expressions to evaluate
and return. The syntax looks like:

test-expression ? yes-expression: no-expression;

The value of this expression is the result of yes-expression if test-expression is true; otherwise, it
is the same as no-expression. For example, the following expression assigns to $max_num either
$first_num or $second_num, whichever is larger: $max_num = $first_num > $second_num ?
$first_num : $second_num;

Example:-

<?php

$x=2;

$y=10; If $y%$x>3?‖$y value is more than 3 folds of


$x‖:‖$y is not large enough‖;

?>

1.6. Manipulate Strings


PHP has many functions to work with strings. The most commonly used functions for searching
and modifying strings are those that use regular expressions to describe the string. The followings
are string manipulation operations:-

i. String concatenation operation: - To concatenate two string variables together, use the
dot (.) operator like echo $string1 . " " . $string2;
ii. strpos() function:- used to search for a string or character within a string. If a match is
found in the string, this function will return the position of the first match. If no match is
found, it will return FALSE.
Written as strops(orginal string, new string) Example: the following
code used to show from where the word ―world‖ started.

Prepared by Amanuel Tadiwos Page 16


Lecture Note: Advanced internet programming 2015 E.C
<?php
echo strpos("Hello world!","world");
?>
The output will be 6. As seen 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.
iii. The strrev( ) function:- takes a string and returns a reversed copy of it.
Has a syntax:-
$string =
strrev(string);
For example: echo
strrev("study hard");
drah yduts
iv. The strlen() function:- is used to find the length of a string. For example:- To find the length of
"Hello world!", we can write as follows
<?ph
echo strlen("Hello world!");
?>
(Reading Assignment)

There are many string function in php.

Prepared by Amanuel Tadiwos Page 17


Lecture Note: Advanced internet programming 2015 E.C

Unit 2: PHP Statements and Form Creations

2.1. PHP statements: - Use Conditionals/Decision Making, LOOP, Arrays

2.1.1. Conditionals/Decision Making Statements


The if, elseif ...else and switch statements are used to take decision based on the different
condition.
The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is
false.
We use this statement if we want to execute a set of code when a condition is true and
another if the condition is not true Syntax if (condition) code to be executed if condition
is true;
else code to be executed if condition is false;
Example
<?php
$x = "Amanuel";
if ($x == "Dani")
{
echo 'Hello Dani!';
} else {
echo 'You are not Dani ! are you Amanuel?';
echo ―yes, you are my friend‖;
}
?>
The ElseIf Statement
If you want to execute some code if one of several conditions is true use the elseif statement
This statement uses to execute a set of code if one of several condition are true
Syntax
if (condition) code to be executed if condition is true;
elseif (condition) code to be executed if condition is true;
else code to be executed if condition is false;

Prepared by Amanuel Tadiwos Page 18


Lecture Note: Advanced internet programming 2015 E.C

If more than one line should be executed in a condition of true/false, the lines should be enclosed
within curly braces as shown below.
Example
<?php
$d=date("D");
if ($d=="Fri"){
echo "Have a nice weekend!";
echo “have good refreshment”;
}
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>

The Switch Statement


Avoid long blocks of if..elseif..else code.
Could execute one of many blocks of code / output
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1: code to be executed if
expression = label1; break;
case label2: code to be executed if
expression = label2; break;
case label n: default: code to be executed if
expression is different from both label1 and
label n;
}
Example:

Prepared by Amanuel Tadiwos Page 19


Lecture Note: Advanced internet programming 2015 E.C

<?php $name=‖kal‖; switch ($name)


{
case "esayas" :
echo "you are esayas "; break;
case "Adane" :
echo "you are adane"; break;
case " eyob " :
echo "you are eyob "; break;
case "kal" :
echo "you are a fantastic person"; break;
default :
echo "Unknown Person‖;"; break;
}
?>

2.1.2. PHP Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following loop types with continue and break keywords which uses to control the
loops execution.

 for - loops through a block of code a specified number of times.


 while - loops through a block of code if and as long as a specified condition is true.
 do...while - loops through a block of code once, and then repeats the loop as long as a
special condition is true.
 foreach - loops through a block of code for each element in an array.

While Loop

• The while loop executes a block of code as long as the specified condition is true.

Syntax

while (condition is true) {


code to be executed; }

Prepared by Amanuel Tadiwos Page 20


Lecture Note: Advanced internet programming 2015 E.C

The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long
as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):

 Example
<?php $x=1;
while($x<=5) {
echo "The number is: $x <br>";
$x++;
}
?>

Do…While Loop

The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.

Syntax

do { code to be executed;

} while (condition is true);

The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?),
and the loop will continue to run as long as $x is less than, or equal to 5:

Example
<?php $x=1; do {
echo "The number is:
$x <br>";
$x++;
} while ($x<=5); ?>

Notice that in a do while loop the condition is tested AFTER executing the statements within the loop.
This means that the do while loop would execute its statements at least once, even if the condition fails
the first time.

Prepared by Amanuel Tadiwos Page 21


Lecture Note: Advanced internet programming 2015 E.C

PHP for Loops

 PHP for loops execute a block of code a specified number of times.


Syntax

for (init counter; test counter;


increment counter) { code to be
executed;
}

Parameters:

• init counter: Initialize the loop counter value


• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value

Example

<?php
for ($x=0; $x<=10; $x++)
{
echo "The number is: $x <br>";
}
?>

The PHP for each Loop

 The for each loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

For each ($array as $value)


{ code to be executed; }

For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.

Prepared by Amanuel Tadiwos Page 22


Lecture Note: Advanced internet programming 2015 E.C

Example

<?php
$colors =array("red","green","blue","yellow");
for each ($colors as $value) { echo "$value
<br>";
}
?>

Php Arrays

 An array stores multiple values in one single variable:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " .
$cars[1] . " and " . $cars[2] .
".";

?>

What is an Array?

An array is a special variable, which can hold more than one value at a time.

Create an Array in PHP

In PHP, the array() function is used to create an array:

• array();

In PHP, there are three types of arrays:

• Indexed arrays - Arrays with numeric index


• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays

Prepared by Amanuel Tadiwos Page 23


Lecture Note: Advanced internet programming 2015 E.C

PHP Indexed Arrays

There are two ways to create indexed arrays:

• The index can be assigned automatically (index always starts at 0):

$cars=array("Volvo","BMW","Toyota");

• or the index can be assigned manually:

$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";

Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " .
$cars[1] . " and " . $cars[2] . ".";

?>

Get The Length of an Array - The count() Function

The count() function is used to return the length (the number of elements) of an array:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like this:

Example

Prepared by Amanuel Tadiwos Page 24


Lecture Note: Advanced internet programming 2015 E.C

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++) {
echo
$cars[$x];
echo
"<br>";
}
?>

PHP Associative Arrays

• Associative arrays are arrays that use named keys that you assign to them.
• There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

Example

<?php
$age=array("Peter"=>"35","Ben"=>"3
7","Joe"=>"43"); echo "Peter is "
. $age['Peter'] . " years old.";
?>

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

Example

<?php
$age=array("Peter"=>"35","Ben"=>"3
7","Joe"=>"43"); foreach($age as
$x=>$x_value) { echo "Key=" .

Prepared by Amanuel Tadiwos Page 25


Lecture Note: Advanced internet programming 2015 E.C

$x . ", Value=" . $x_value;


echo "<br>";
}
?>

MULTIDIMENSIONAL ARRAYS (READING ASSIGNEMENTS)


2.2 PHP GET, POST & REQUIST Methods

Usually used when we create forms to make communication between interfaces and
databases.
The GET Method:-
 Has restriction to send to server/ database parts up to 1024 characters only.
 GET can't be used to send binary data, like images or word documents, to the server
because the GET method sends the encoded user information.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable. Never use GET method for systems which have password or other sensitive
information to be sent to the server.
 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) For example [Link]

Example:- let we save as [Link]

<?php
if($_GET["name"] || $_GET["age"])
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>

Prepared by Amanuel Tadiwos Page 26


Lecture Note: Advanced internet programming 2015 E.C

<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

The above code‘s action attribute value can be represented as the file names itself like:-
<form action=”[Link]” method=”Get”>

The POST Method

The POST method transfers information via HTTPs headers. The information is encoded as described in
case of GET method and put into a header called QUERY_STRING.

 The POST method does not have any restriction on data size to be sent.
 Relatively secured and could large data in requesting and responding data
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header is secured enough on HTTP protocol.
The PHP provides $_POST associative array to access all the sent information using POST
method.
 Variables sent with HTTP POST are not shown in the URL
 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 For example
[Link]

Example:- as example, we could change GET by post from example.

The $_REQUEST variable

 The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and
$_COOKIE variables

Prepared by Amanuel Tadiwos Page 27


Lecture Note: Advanced internet programming 2015 E.C

 This variable can be used to get the result from form data sent with both the GET and
POST methods.

Example:- <?php

if( $_REQUEST["name"] || $_REQUEST["age"] )


{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age'].
" years old.";
exit(); }
?><html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

2.3 Creating PHP Forms


 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 PHP scripts. It
works as follows:-

Prepared by Amanuel Tadiwos Page 28


Lecture Note: Advanced internet programming 2015 E.C

 The syntax could be written as -

<form action= ”url to submit the form filled” method=


“get” or “post” or “request”>
<!–- form contents -->
</form>

 Where

• action=―…‖ is the page that the form should submit its data to, and
• method=―…‖ is the method by which the form data is submitted. If the method
is get the data is passed in the url string, if the method is post it is passed as a
separate file.

The form variables are available to PHP in the page to which they have been submitted. The
variables are available in two superglobal arrays created by PHP called $_POST and $_GET.

The basic concept that is important to understand is that any form element will automatically be
available to PHP scripts. See the following example:

<form action="[Link]" method="post">


Your name: <input type="text" name="name" />
Your age: <input type="text" name="age" />
<input type="submit" />

Prepared by Amanuel Tadiwos Page 29


Lecture Note: Advanced internet programming 2015 E.C

</form>
When the user fills in this form and hits the submit
button, the [Link] page is called. In this file we
would write something like this:
<?php echo (―you are
($_POST['name']‖);
echo $_POST['age'];
years old.
?>

2.4 Form Validation

If a user who forgot to enter one of the fields or enter wrong input, we need to validate the form to
make sure it‘s complete and filled out with valid information. We can use JavaScript for this
validation. Validations can also be done with simple PHP if statements as shown below.

When the process is done, if it is done making validations, it will check to see if there is an error
message. If there is, it displays the error message. If there are no errors, it displays a success
message.

<Html>
<Body>
<form action="[Link]" method="post">
Your Name: <input type="text"
name="yourname" /><br /> E-mail:
<input type="text" name="email"
/><br/> <p>Do you like this website?
<input type="radio" name="likeit" value="Yes"
checked="checked" /> Yes
<input type="radio" name="likeit" value="No" /> No
<input type="radio" name="likeit" value="Not sure" /> Not
sure</p><br/>
<p>Your comments:<br />

Prepared by Amanuel Tadiwos Page 30


Lecture Note: Advanced internet programming 2015 E.C

<textarea name="comments" rows="10"


cols="40"></textarea></p>
<p><input type="submit" value="Send!"></p>
</form>
</body>
</html>

Note that:- from the above code,

 All variables passed to the current script via the HTTP POST method are stored in
associative array $_POST. For example, in PHP we can access data from each field using
$_POST['NAME'], where NAME is the actual field name.
 If we submit the above form, we would have access to a number of $_POST array values
inside the [Link] file:

In php, we can check the validity of inputs such as URL, E-mail, digits, letters and other special
characters etc using functions. For example preg_match() function used to match list of inputs with
defined lists. For example, see the following rules:-

i. URL Address:- If there is an input field named "website" we can check for a valid URL
address like this:
$url =
htmlspecialchars($_POST['website'])
; if
(!preg_match("/^(https?:\/\/+[\w\-
]+\.[\w\-]+)/i",$url)) { die("URL
address not valid"); }

From the code given above, if the input held by $url is not match with the given string , then the
die() function force the system to terminate the running .
ii. Digits 0-9 only: - This uses to check whether an input is digit/ number or not.

The following is a syntax to check if $age is a number or not. If not number, it display
―Please enter numbers only for Age‖ .

Prepared by Amanuel Tadiwos Page 31


Lecture Note: Advanced internet programming 2015 E.C
$age=
htmlspecialchars($_POST['age
']); if
(!preg_match("/\D/",$age)) {
die("Please enter numbers
only for Age");
}

iii. Validate e-mail address:- Used to check an email is valid, i.e to have valid forms.
There is a simple way to check if data entered into input field named "email" is an e-mail
address without any unnecessary complications and fancy regular expressions.
$email = htmlspecialchars($_POST['email']); if
(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-
]+)/",$email)) { die("E-mail address not valid");
}
iv. Letters a-z and A-Z only:- This code will check if $text is made of letters a-z and A-Z
only (no spaces, digits or any other characters): $name = test_input($_POST["name"]);
if (preg_match("/[^a-zA-Z]/",$text)) { die("Please enter letters a-z and A-Z only!"); }

Please read Lab tutorials more about the forms and form validations.

Prepared by Amanuel Tadiwos Page 32


Lecture Note: Advanced internet programming 2015 E.C

Chapter 3 Files and Directories in PHP

3.1. Reading files/ Directories

Files and directories have three levels of access: User, Group and Other. The three typical
permissions for files and directories are: Read (r), Write (w) and Execute (x) A stream is a channel
used for accessing a resource that we can read from and write to. The input stream reads data from
a resource (such as a file) while the output stream writes data to a resource.

Once a file is opened using fopen() function it can be read with a function called fread(). This
function requires two arguments. These must be the file pointer and the length of the file expressed
in bytes. The file‘s length can be found using the filesize() function which takes the file name as
its argument and returns the size of the file expressed in bytes.

So here are the steps required to read a file with PHP.

 Open a file using fopen() function. Syntax:- variable= fopen(―text file‖, ―mode‖);
where mode mean r, r+, w, w+ etc as shown in the next page.
 Get the file's length using filesize() function. The syntax is filesize($filename );
 Read the file's content using fread() function. Has syntax variable = fread( filename,
filesize);
 Close the file with fclose() function. It uses when finished working with a file stream to
save space in memory.
Syntax:- fclose(file name that contains the opened files);
$handle from the following example.

Example:- Files modes can be specified as one of the six options in this table.
Mode Descriptions /Purpose

r Opens the file for reading only. Places the file pointer at the beginning of the file.
r+ Opens the file for reading and writing. Places the file pointer at the beginning of the
file.
w Opens the file for writing only. Places the file pointer at the beginning of the file. and
truncates the file to zero length. If files does not exist then it attempts to create a file.

Prepared by Amanuel Tadiwos Page 33


Lecture Note: Advanced internet programming 2015 E.C

w+ Opens the file for reading and writing only. Places the file pointer at the beginning of
the file. And truncates the file to zero length. If files does not exist then it attempts to
create a file.
A Opens the file for writing only. Places the file pointer at the end of the file. If files
does not exist then it attempts to create a file.
a+ Opens the file for reading and writing only. Places the file pointer at the end of the
file. If files does not exist then it attempts to create a file.

Creating Directories in PHP

• A new directory can be created in PHP using the mkdir() function.


• This function takes a path to the directory to be created.
• To create a directory in the same directory as your PHP script simply provide the
directory name.
• To create a new directory in a different directory specify the full path when calling
mkdir().

<?php

$result = mkdir ("/path/to/directory", "0777");

?>

Deleting a Directory

• Directories are deleted in PHP using the rmdir() function.


• rmdir() takes a single argument, the name of the directory to be deleted.
• The deletion will only be successful if the directory is empty.
• If the directory contains files or other sub-directories the deletion cannot be performed
until those files and sub-directories are also deleted.

Read files in PHP

• The fread() function reads from an open file.

Prepared by Amanuel Tadiwos Page 34


Lecture Note: Advanced internet programming 2015 E.C

• The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
• Example:-
<?php
$myFile = "[Link]";
$fh = fopen($myFile, 'r');
$myFileContents =
fread($fh,filesize("[Link]"));
fclose($fh);
echo $myFileContents;
?>

Write to File in PHP

• The fwrite() function is used to write to a file.


• The first parameter of fwrite() contains the name of the file to write to and the second parameter
is the string to be written.
• Example:
<?php
$myFile2 = "[Link]";
$myFileLink2 = fopen($myFile2, 'a') or die("Can't open file.");
$newContents = "I am a student";
fwrite($myFileLink2, $newContents);
fclose($myFileLink2);
?>

Open File in PHP

• A better method to open files is with the fopen() function.


• The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened.

Prepared by Amanuel Tadiwos Page 35


Lecture Note: Advanced internet programming 2015 E.C

3.2. Upload Files

• Web applications allow visitors to upload files to and from their local computer. The files that are
uploaded and downloaded may be simple text files or more complex file types, such as images,
documents, or spreadsheets
• Files are uploaded through an HTML form using the ―post‖ method and enctype attribute with
value of ―multipart/form-data,‖ which instructs the browser to post multiple sections – one for
regular form data and one for the file contents.
• The file input field creates a browser button for the user to navigate to the appropriate file to
upload <form method=‖post‖ action=‖ ‖ enctype= multipart/form-data >
<input type="file" name="picture_file" /> </form>
• The MAX_FILE_SIZE (uppercase) attribute of a hidden form field specifies the maximum
number of bytes allowed in the uploaded file and it must appear before the file input field.
• When the form is posted, information for the uploaded file is stored in the $_FILES auto global
array.
• Example:-The following HTM code below creates an uploaded form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
<html> <body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
<?php
if( $_FILES['file']['name'] != "" ){
copy( $_FILES['file']['name'],
"C:\wamp\www\Leture\[Link]" ) or die( "Could not
copy file!");

Prepared by Amanuel Tadiwos Page 36


Lecture Note: Advanced internet programming 2015 E.C

}
else
{
die("No file specified!");}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
</body></html>

3. 3 PHP Cookies and Session


What is a Cookie?

• 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.

Create Cookies With PHP

• A cookie is created with the setcookie() function.

Syntax

• setcookie(name, value, expire, path, domain, secure, httponly);

Prepared by Amanuel Tadiwos Page 37


Lecture Note: Advanced internet programming 2015 E.C

• Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie

• The following example creates a cookie named "user" with the value "John Doe". The
cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available
in entire website (otherwise, select the directory you prefer).
• We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).
We also use the isset() function to find out if the cookie is set:

Note: The setcookie() function must appear BEFORE the <html> tag.

Example

<?php
$cookie_name = "user";
$cookie_value = "John
Doe";
setcookie($cookie_name, $cookie_value, time() + (86400
* 30), "/"); // 86400 = 1 day ?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else { echo "Cookie '" .
$cookie_name . "' is set!<br>";
echo "Value is: " .
$_COOKIE[$cookie_name];
}
?>
</body>
</html>

Prepared by Amanuel Tadiwos Page 38


Lecture Note: Advanced internet programming 2015 E.C

PHP Session

• A session is a way to store information (in variables) to be used across multiple pages.
• Unlike a cookie, the information is not stored on the users computer.
• Session variables hold information about one single user, and are available to all pages in
one application.
• If you need a permanent storage, you may want to store the data in a database.
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.

Example

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

Note: The session_start() function must be the very first thing in your document. Before
any HTML tags.

Get PHP Session Variable Values

Prepared by Amanuel Tadiwos Page 39


Lecture Note: Advanced internet programming 2015 E.C

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were
set on previous page echo "Favorite
color is " . $_SESSION["favcolor"] .
".<br>"; echo "Favorite animal is " .
$_SESSION["favanimal"] . ".";
?>
</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables session_unset(); // destroy
the session session_destroy();
?>

Prepared by Amanuel Tadiwos Page 40


Lecture Note: Advanced internet programming 2015 E.C

</body>
</html>

3.4 PHP - File Inclusion


You can include the content of a PHP file into another PHP file before the server executes it. There are
two PHP functions which can be used to included one PHP file into another PHP file.

The include() Function The require() Function

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be
reused on multiple pages. This will help developers to make it easy to change the layout of complete
website with minimal effort. If there is any change required then instead of changing thousand of files just
change included file.

The include() Function

 The include() function takes all the text in a specified file and copies it into the file that uses the
include function.
 If there is any problem in loading a file then the include() function generates a warning but the
script will continue execution.
 Assume you want to create a common menu for your website. Then create a file [Link] with
the following content.
<a href="[Link]
<a href="[Link]
<a href="[Link]
<a href="[Link] <br />

Now create as many pages as you like and include this file to create header. For example now your
[Link] file can have following content.

<html>
<body>
<?php
include("[Link]");
?>

Prepared by Amanuel Tadiwos Page 41


Lecture Note: Advanced internet programming 2015 E.C

<p>This is an example to show how to include PHP file!</p>


</body>
</html>

The require() function

 The require() function takes all the text in a specified file and copies it into the file
that uses the include function. If there is any problem in loading a file then the
require() function generates a fatal error and halt the execution of the script.
 So there is no difference in require() and include() except they handle error
conditions.
 It is recommended to use the require() function instead of include(), because scripts
should not continue executing if files are missing or misnamed.
 You can try using above example with require() function and it will generate same
result. But if you will try following two examples where file does not exist then you
will get different results.
<html>
<body>
<?php
include("[Link]");
?>
<p>This is an example to show how to include wrong PHP file!</p> </body>
</html>

Output:- This is an example to show how to include wrong PHP file!

<html>
<body>
<?php
require("[Link]");
?>
<p>This is an example to show how to include wrong PHP
file!</p>

Prepared by Amanuel Tadiwos Page 42


Lecture Note: Advanced internet programming 2015 E.C

</body>
</html>

Output:-This time file execution halts and nothing is displayed.

NOTE:-You may get plain warning messages or fatal error messages or nothing at all. This
depends on your PHP Server configuration.

Prepared by Amanuel Tadiwos Page 43


Lecture Note: Advanced internet programming 2015 E.C

Chapter 4:- PHP Database / PHP with MYSQL


 With PHP, you can connect to and manipulate databases.

 MySQL is the most popular database system used with PHP.

What is MySQL?

 MySQL is a database system used on the web


 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation

The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.

Database Queries

 A query is a question or a request.


 We can query a database for specific information and have a recordset returned.
 Example: SELECT LastName FROM Employees

Connecting to databases

To connect PHP with database, four important things must be taken place. Those
are:-

Define constants
 Create connection using mysql_connect.
 Select database.
 Close connection.

Prepared by Amanuel Tadiwos Page 44


Lecture Note: Advanced internet programming 2015 E.C

4.1. Define constants

To connect php with database, defining constants is very important. Constants that must be
defined are:-

 Define the server.

 Define user name of the server.

 Define password of the user. Define database name.

To define the constant, we can use as follows:


<?php define("db_server","localhost");// the server that
we use define("db_user","root");// the username of the
server define("db_pass","");//password of the server
define("db_name","schoolmgt");//the database that we use
?>

4.2. Opening Database Connection

After defining constants using php, opening or creating connection is very important. To open or create
database connection, we use mysql_connect function.

This function takes three parameters. Those are:

db_server,db_user,db_pass.
 Db_server:-The host name running database server
 Db_user:-The username accessing the database
 Db_pass:-The password of the user accessing the database.

From the above the host name running database server is ―localhost‖, the username accessing
the database is ―user‖, and the password of the user accessing the database is empty. Connection
can opened or created as follows:

$connection=mysql_connect(db_server,db_user,db_pass);

Prepared by Amanuel Tadiwos Page 45


Lecture Note: Advanced internet programming 2015 E.C

4.3. Select database

Once you establish a connection with a database server then it is required to select a particular
database where your all the tables are associated.

This is required because there may be multiple databases residing on a single server and you can
do work with a single database at a time.

To select database, we use mysql_select_db as follows:-

$db_select=mysql_select_db(db_name,$connection);

4. Closing database connection

Its simplest function mysql_close PHP provides to close a database connection. This function
takes connection resource returned by mysql_connect function. For example, to close the
connection that you use in the above; you use mysql_close function as follows:-
mysql_close($connection);
Create MySQL Database Using PHP

To create and delete a database you should have admin privilege. Its very easy to create a new
MySQL database. PHP uses mysql_query function to create a MySQL database. For example to
create the database test_db using php, you can write as follows:-

<?php
define("db_server","loca
lhost");
define("db_user","root")
; define("db_pass","");
$connection=mysql_connect(db_server,db_user,db
_pass); if(!$connection)
{ die("error connection to db
server".mysql_error());
} echo ―Connected
successfully‖;

Prepared by Amanuel Tadiwos Page 46


Lecture Note: Advanced internet programming 2015 E.C

$sql = ―CREATE Database


test_db‖; $retval =
mysql_query( $sql,
$connection);
if(! $retval ) { die('Could
not create database: ' .
mysql_error());
} echo "Database test_db
created successfully\n";
mysql_close $connection);
?>

Creating Database Tables

To create tables in the new database you need to do the same thing as creating the database. First create
the SQL query to create the tables then execute the query using mysql_query() function.

<?php define("db_server","localhost"); define("db_user","root");


define("db_pass",""); define("db_name","test_db");
$con=mysql_connect(db_server,db_u
ser,db_pass); if(!$con){ die("not
connected".mysql_query());
}

$sqldb=mysql_select_db(db_na
me,$con); if (!$sqldb){
die("incorrectly
selected".mysql_error());
}

$sql = 'CREATE TABLE employee( '.

'emp_id INT NOT NULL AUTO_INCREMENT, '.

'emp_name VARCHAR(20) NOT NULL, '.

'emp_address VARCHAR(20) NOT NULL, '.

Prepared by Amanuel Tadiwos Page 47


Lecture Note: Advanced internet programming 2015 E.C
'emp_salary INT NOT NULL, '.

'join_date timestamp(14) NOT NULL, '.

'primary key (
emp_id ))';
$retval =
mysql_query($sql,$con);
if(!$retval ) {
die('Could not create table: ' .
mysql_error());
}

echo "Table employee created successfully\n";

?>

In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and execute those commands.
Consider the following content in sql_query.txt file.

CREATE TABLE employee


(emp_id INT NOT NULL
AUTO_INCREMENT, emp_name
VARCHAR(20) NOT NULL,
emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
join_date timestamp(14) NOT NULL,
primary key ( emp_id ));

<?php
define("db_server","localhost");
define("db_user","root");
define("db_pass","");
define("db_name","test_db");
$con=mysql_connect(db_server,db_u

Prepared by Amanuel Tadiwos Page 48


Lecture Note: Advanced internet programming 2015 E.C
ser,db_pass); if(!$con){ die("not
connected".mysql_query());
}

$sqldb=mysql_select_db(db_na
me,$con); if (!$sqldb){
die("incorrectly
selected".mysql_error());
}

$query_file = 'sql_query.txt';

$fp = fopen($query_file,
'r'); $sql = fread($fp,
filesize($query_file));
fclose($fp);
$retval = mysql_query($sql,$con);

if(!$retval ) {
die('Could not create table: '.mysql_error());

echo "Table employee created successfully\n";

?>

Insert Data into MySQL Database

Data can be entered into MySQL tables by executing SQL INSERT statement through PHP function
mysql_query. Below a simple example to insert a record into employee table. sql = 'INSERT INTO
employee '.

'(emp_name,emp_address, emp_salary, join_date) '.

'VALUES ( "guest", "XYZ", 2000, NOW() )';

Prepared by Amanuel Tadiwos Page 49


Lecture Note: Advanced internet programming 2015 E.C

Getting Data From MySQL Database

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function
mysql_query. You have several options to fetch data from MySQL.

The most frequently used option is to use function mysql_fetch_array(). This function returns row as an
associative array, a numeric array, or both. This function returns FALSE if there are no more rows. next
is a simple example to fetch records from employee table.

$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

$retval = mysql_query($sql,$con);

if(!$retval ) {
die('Could not create table: ' .
mysql_error());
}

while($row = mysql_fetch_array($retval,
MYSQL_ASSOC)) { echo "EMP ID
:{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".

"EMP SALARY : {$row['emp_salary']} <br> ".

"--------------------------------<br>";

The content of the rows are assigned to the variable $row and the values in row are then
[Link] remember to put curly brackets when you want to insert an array value directly
into a string.

In above example the constant MYSQL_ASSOC is used as the second argument to


mysql_fetch_array(), so that it returns the row as an associative array. With an associative array
you can access the field by using their name instead of using the index.

Prepared by Amanuel Tadiwos Page 50


Lecture Note: Advanced internet programming 2015 E.C

PHP provides another function called mysql_fetch_assoc() which also returns the row as an
associative array.

Using mysql_fetch_assoc() while($row =


mysql_fetch_assoc($retval)) {
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".

"EMP SALARY : {$row['emp_salary']} <br> ".

"--------------------------------<br>";

Using MYSQL_NUM

while($row = mysql_fetch_array($retval,
MYSQL_NUM)) { echo "EMP ID :{$row[0]}
<br> ".
"EMP NAME : {$row[1]} <br> ".

"EMP SALARY : {$row[2]} <br> ".

"--------------------------------<br>";

Deleting Data from MySQL Database

Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP function
mysql_query.

Below is a simple example to delete records into employee table. To delete a record in any table it is
required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.

$emp_id = $_POST['emp_id'];

$sql = "DELETE FROM employee WHERE emp_id= $emp_id" ;

Prepared by Amanuel Tadiwos Page 51


Lecture Note: Advanced internet programming 2015 E.C

Deleting MySQL Database and table Using PHP

If a database is no longer required then it can be deleted forever. You can use pass an SQL command to
mysql_query to delete a database.

$sql = 'DROP DATABASE test_db‘; --- deleting MySQL database

$sql = 'DROP TABLE employee‘; ------ deleting table

Updating Data into MySQL Database

Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function
mysql_query.

Below is a simple example to update records into employee table. To update a record in any table it is
required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.

$emp_id=$_POST['emp_id‘];

$emp_salary = $_POST['emp_salary‘];

$sql = "UPDATE employee ". "SET emp_salary = $emp_salary ".


"WHERE emp_id = $emp_id" ;

Prepared by Amanuel Tadiwos Page 52

Common questions

Powered by AI

Server-side scripts enhance web page interactivity and user experience by dynamically generating content based on user interactions and data inputs. These scripts allow customization of web pages according to user preferences, access privileges, or historical data, creating a personalized experience. Server-side scripting can also manage complex data operations such as retrieving and displaying data from databases in real-time, which is crucial for interactive applications like e-commerce sites. By offloading data processing to the server, developers can create more efficient interactions and streamline user experiences with less reliance on client-side resources .

PHP handles form data by utilizing superglobal arrays $_GET and $_POST, which store data sent through corresponding HTTP methods. When submitting a form with the GET method, PHP collects data appended to the URL and stores it in the $_GET array, making it accessible in the script using $_GET['fieldname']. For the POST method, PHP stores data in the $_POST array, sent via HTTP headers, and retrieves it using $_POST['fieldname']. The process involves specifying the method in the HTML form tag, which dictates how the server receives the data, enabling PHP to process or validate the incoming user input accordingly. The choice between GET and POST affects data security, visibility, and the amount of data transferable .

Client-side scripting involves code execution by the user's web browser and is typically used for creating interactive features within a webpage. These scripts are visible to the user and run after the page has been loaded, often allowing users to manipulate page content without reloading. Common client-side scripting languages include JavaScript and HTML. In contrast, server-side scripting occurs on the web server, where the script is executed before the content is delivered to the user's browser. The resulting output is typically in HTML, which the browser displays. Server-side scripting languages, such as PHP, Java, and ASP.NET, provide dynamic responses based on user input and interaction with databases, thereby offering more control over website behavior and data security .

PHP indexed arrays are collections of values assigned indices starting from zero, either automatically or manually. For instance, an indexed array $cars can be created as $cars = array('Volvo', 'BMW', 'Toyota');. This allows for accessing elements using numeric indices, e.g., $cars[0] returns 'Volvo'. Associative arrays, on the other hand, use named keys instead of numeric indices, allowing elements to be accessed by their key names. An example of an associative array is $age = array('Peter' => 35, 'Ben' => 37, 'Joe' => 43);, where $age['Peter'] returns the value 35. The choice between the two depends on whether the data is more meaningfully represented by numeric indices or descriptive keys .

PHP can restrict user access to specific web pages by implementing session-based authentication measures. This can be achieved by starting a session on the server and storing user roles or access privileges when they log in. For example, a PHP script can check if a session variable, such as $_SESSION['user_role'], matches the required role for accessing a particular page. If the condition fails, the script can redirect users to an access denied page or require re-authentication. This approach ensures that only authorized users, whose session indicates the necessary privileges, can access sensitive content .

The GET method is less appropriate in scenarios requiring the transmission of sensitive information, such as passwords, due to its inclusion of request data in the URL, making it visible and less secure. It is also limited by the URL length restriction, which is unsuitable for large amounts of data or files. Furthermore, GET is less optimal for modification operations due to the semantics associated with retrieving data, not changing it. The POST method, which sends data through HTTP headers, is preferred for secure and large data transactions as its data does not appear in the URL and has no size limitations compared to GET .

The count() function in PHP is used to determine the number of elements in an array or count the number of properties in an object implementing Countable interface. This function can be particularly useful in loops to calculate the number of iterations needed when processing array elements. For example, in a for loop iterating over an indexed array, count() can determine the stopping condition: for($i = 0; $i < count($array); $i++) {...}. This offers a way to dynamically handle arrays without hardcoding the array size, thus providing flexibility in code management particularly for applications dealing with data manipulation or dynamically-changing datasets .

Server-side scripting provides significant security advantages over client-side scripting because the source code executed on the server is not visible to the end user, reducing the risk of code tampering or exposure to potential attacks. Server-side scripts also restrict direct access to sensitive operations by validating user requests on the server, where code can be managed more securely. In contrast, client-side scripts are downloaded and executed on the user's browser, making them accessible and potentially modifiable by users, which could lead to security vulnerabilities if not properly managed .

PHP can perform several common file handling tasks on a web server, including creating, opening, reading, writing, and closing files. PHP scripts can upload files from a user to the server, process their content, and store the data in various formats. It also allows listing directory contents and managing file permissions. This versatility makes PHP a powerful tool for managing web-based applications that rely on file manipulation and storage .

PHP facilitates interactions with databases by abstracting the complexities of database connectivity and queries, allowing programmers to execute database operations using simple instructions. PHP supports multiple database management systems, including MySQL, Oracle, PostgreSQL, and Microsoft SQL Server, making it versatile for various application requirements. It simplifies database interactions by handling connectivity, data exchange, and query execution, allowing developers to focus on application logic without delving into the specifics of each database technology .

You might also like