Web Design, Programmig and Administration
Web Design, Programmig and Administration
COURSE CODE:
UNIT 1 : INTRODUCTION
All students should be familiar with the concepts of html and cascading stylesheets.
• A code editor. A code editor is a text editor that is specifically designed for writing code. It
provides features such as syntax highlighting, code completion, and debugging tools. Some
popular code editors include Visual Studio Code, Sublime Text, and Atom.
• A web development environment (WDE). A WDE is a software environment that allows you to
develop web applications locally on your computer. It includes a web server, database server,
and PHP interpreter. Some popular WDEs include WAMP,XAMPP, LAMP, and MAMP.
• A web browser. A web browser is used to view the results of your PHP code. Any modern web
browser, such as Google Chrome, Mozilla Firefox, or Microsoft Edge, will work.
• A version control system (VCS). A VCS is a system that allows you to track changes to your
code and collaborate with other developers. Some popular VCSs include Git and Mercurial.
• A debugger. A debugger is a tool that allows you to step through your code line by line and
inspect the values of variables. This can be helpful for finding and fixing bugs in your code.
Some popular debuggers include Xdebug and PHP Debugger.
• A documentation generator. A documentation generator is a tool that can generate
documentation for your PHP code. This can be helpful for documenting your code and making it
easier to understand and maintain. Some popular documentation generators include
phpDocumentor and Sphinx.
PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used,
free, and efficient alternative to competitors such as Microsoft's ASP.
What is PHP?
It allows web developers to create dynamic content that interacts with databases. PHP is
basically used for developing web based software applications.
• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, etc.)
What is MySQL?
• MySQL compiles on a number of platforms. PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a
Unix platform). PHP runs on different platforms (Windows, Linux, Unix, etc.)
Three are the main areas where PHP scripts are used:
• Server-side scripting
This is the most used and main target for PHP. You need three things to make this work the way
you need it. The PHP parser (CGI or server module), a web server and a web browser.
You need to run the web server where You can access the PHP program output with a web
browser, viewing the PHP page through the server. All these can run on your home machine if
you are just experimenting with PHP programming.
You can make a PHP script to run it without any server or browser. You only need the PHP
parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on
Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text
processing tasks.
PHP may not the very best language to create a desktop application with a graphical user
interface, but if you know PHP very well, and would like to use some advanced PHP features in
your client-side applications you can also use PHP-GTK to write such programs. You also have
the ability to write cross-platform applications this way. In this article, we’ll have a detailed look
at the server-side scripting using PHP.
Why PHP?
A web server is an information technology that processes requests via HTTP, the basic network
protocol used to distribute information on the World Wide Web. There exist many types of web
servers that servers use. Some of the most important and well-known are: Apache HTTP Server,
IIS (Internet Information Services), lighttpd, Sun Java System Web Server etc. As a matter of
fact, PHP is compatible with all these web servers and many more.
Unlike some technologies that require a specific operating system or are built specifically for
that, PHP is engineered to run on various platforms like Windows, Mac OSX, Linux, Unix etc)
An important reason why PHP is so used today is also related to the various databases it supports
(is compatible with). Some of these databases are: DB++, dBase, Ingres, Mongo, MaxDB,
MongoDB, mSQL, Mssql, MySQL, OCI8, PostgreSQL, SQLite, SQLite3 and so on.
Anyone can start using PHP right now by downloading it from php.net. Millions of people are
using PHP to create dynamic content and database-related applications that make for outstanding
web systems. PHP is also open source, which means the original source code is made freely
available and may be redistributed and modified.
PHP is a simple language to learn step by step. This makes it easier for people to get engaged in
exploring it. It also has such a huge community online that is constantly willing to help you
whenever you’re stuck (which actually happens quite a lot).
• Laravel
• Symfony
• Yii
• CodeIgniter
• Laminas Project (formerly Zend Framework)
• CakePHP
• Phalcon
• Slim Framework
• FuelPHP
• PHPPixie
• Fat-Free Framework
• Supported versions:
Advantages of PHP
• It’s fast. Because it is embedded in HTML code, the response time is short.
• It’s inexpensive — free, in fact. PHP is proof that free lunches do exist and that you can
get more than you paid for.
• It’s easy to use. PHP contains many special features and functions needed to create
dynamic Web pages. The PHP language is designed to be included easily in an HTML
file.
• It can run on many operating systems. It runs on a variety of operating systems —
Windows, Linux, Mac OS, and most varieties of Unix.
• It’s available on almost all Web hosts. If you are going to publish your Web site on a
Web host, you will find PHP installed on almost all Web hosts for free.
• Technical support is widely available. A large base of users provides free support
through e-mail discussion lists.
• It’s secure. The user does not see the PHP code.
• It’s designed to support databases. PHP includes functionality designed to interact
with specific databases. It relieves you of the need to know the technical details required
to communicate with a database.
• It’s customizable. The open source license allows programmers to modify the PHP
software, adding or modifying features as needed to fit their own specific environments
Learning a new language is not easy. You need to understand not only the syntax of the
language, but also its grammatical rules, that is, when and why to use each element of the
language
PHP code is executed on the server, and the plain HTML result is sent to the browser.
For maximum compatibility, we recommend that you use the standard form
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code
There are four ways the PHP parser engine can differentiate PHP code in a webpage:
• Canonical PHP Tags This is the most popular and effective PHP tag style and looks like this:
<?php…..?>
• Short-open Tags
These are the shortest option, but they might need a bit of configuration, and you might either
choose the --enable-shorttags configuration option when building PHP, or set the short_open_tag
setting in your php.ini file.
• ASP-like Tags
In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:
<%.........%>
You can define a new script with an attribute language like so:
<script language=”php”>……..</script>
The result of the above statements would be the same: "Hello World". But why are there three
different ways to output?
echo and print are more or less the same. They are both used to output data to the screen. The
differences are small: 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.
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. In the example above we have used the echo statement to output the
text "Hello World"
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.
Commenting PHP
Just like other languages, there are several ways to comment PHP code.
Let’s have a look at the most useful ones:
Variables in PHP
Variables are the building blocks of any programming language. A variable can be thought of as
a programming construct used to store both numeric and nonnumeric data. The contents of a
variable can be altered during program execution, and variables can be compared and
manipulated using operators.
A variable is used to store information. Variable names in PHP are case-sensitive. As a result the
variables $color, $Color and $COLOR are treated as three different variables.
Variables are used for storing values, like text strings, numbers or arrays. When a variable is
declared, it can be used over and over again in your script.
$var_name = value;
1. Integers -
▪ They are whole numbers, without a decimal point, like 4195.
▪ They are the simplest type.
▪ They correspond to simple whole numbers, both positive and negative.
Integers can be assigned to variables, or they can be used in expressions,
like $int_var = 12345;$another_int = -12345 + 12345;
▪ Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base
16) format. Decimal format is the default, octal integers are specified with
a leading 0, and hexadecimals have a leading 0x.
2. Doubles –
▪ floating-point numbers like 46.2, 733.21 etc
▪ They like 3.14159 or 49.1. By default, doubles print with the minimum
number of decimal places needed.
3. Booleans -
▪ They have only two possible values either true or false.
▪ PHP provides a couple of constants especially for use as Booleans: TRUE
and FALSE,
4. Strings - set of characters, like KIUT
5. Arrays - named and indexed collections of other values
There are numerous functions available for determining the data type of variables
• getType( )
• is_array( )- Returns true if the argument is an array
• is_double( )- Returns true if the argument is a double
• is_float( ), is_real( )
• is_long( ),
• is_int( )-Returns true if the argument is an integer
• is_string( )- Returns true if the argument is a string
• is_object( )- Returns true if the argument is an object
• is_resource( )- Returns true if the argument is a resource
• is_null( )- Returns true if the argument is null
• is_scalar( ) – check for integer, Boolean, string, or float
• is_numeric( ) – check for number or numeric string
• is_callable( ) – checks for valid function name
• is_bool() -Returns true if the argument is boolean
There is also a settype( $var, ‘type’ ) function that can be used to set a specific type
// Casting
$totalamount = (float)$totalqty;
The following snippet shows all of these data types declared as variables:
<?
$intNum = 472;
$doubleNum = 29.3;
$boolean = true;
$string = ’bcs’;
class person {
function agePrint() {
$age = 5;
?>
• A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and
_)
Variable Scope
• At this point we know that all variables have an identifier, a data type, and a value.
• All variables also have a scope.
o The scope of a variable refers to the places in a script where a variables can be
used.
In PHP, variables can be declared anywhere in the script. The scope of a variable
is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
$x = 5; // local scope
PHP can be used for creating dynamic websites. In a dynamic website, user can
interact with website by providing text or by selecting options. Form is one of the
quickest and easiest ways to add interactivity to our website. Through forms we
can read user data into PHP variables.
Sample form
Home.html
< html>
< head>
< body>
< form action=" message . PHP" method =" post"> Enter your message:
</ form>
</ body>
</ html>
Message. php
<? PHP
// print it
?>
Output
Explanation
Here we have used HTML coding for displaying the input box. The <form> tag of
html isused with input option. The form tag also contains two main attributes
action and method.
The action attribute specifies the name of the script. Here the name is
message.php. The script will process the message entered into the form. The
method attribute of the < form> tag specifies the manner in which form data will
be submitted. Here it is POST method.
We have to run the home.html file in a browser. This is a client side script. On
running this file a form is displayed in the webpage with a line.When we click the
submit button the server side script in the action attribute will be called for
execution. That script will display another webpage that prints the string we have
entered.The $_POST variable would have stored the string we have entered. It
will be stored in $_POST[‘msg’]. Then it will be assigned to php variable
$input.We can display it using echo statement
Constants
Constants are like variables except that once they are defined they cannot be
changed or undefined.
A valid constant name starts with a letter or underscore (no $ sign before the
constant name). Note: Unlike variables, constants are automatically global across
the entire script.
Syntax
Parameters:
<!DOCTYPE html>
<html>
<body>
<?php
echo “GREETING”;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
echo greeting;
?>
</body>
</html>
NOTE
Constants are automatically global and can be used across the entire script.
Operators
a. Arithmetic Operators
b. Assignment Operators
c. Bitwise Operators
d. Comparison Operators
e. Incrementing/Decrementing Operators
f. Logical Operators
g. String Operators
h. Array Operator
The PHP arithmetic operators are used to perform common arithmetic operations
such as addition, subtraction, etc. with numeric values.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".
The bitwise operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.
Comparison Operators
The increment and decrement operators are used to increase and decrease the
value of a variable.
The logical operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.
String Operators
The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:
For example the expression 3+2*3 will first evaluate the product 2*3 and then the
sum, so the result is 9 rather than 15. If you want to perform operations in a
specific order, different from the natural order of precedence, you can force it by
enclosing the operation within parentheses. Hence, (3+2)*3 will first perform the
sum and then the product, giving the result 15 this time
Control structures
▪ Control structure allows you to control the flow of code execution in your
application.
▪ Generally, a program is executed sequentially, line by line, and a control
structure allows you to alter that flow, usually depending on certain
conditions
▪ Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.
▪ Conditional statements are statements that can only be executed when a certain particular
condition is fulfilled.
a) The If statement
The if statement executes a piece of code if a condition is true. The syntax is
if (condition)
{
// code to be executed in case the condition is true
}
<?php
$age = 18;
if ($age < 20)
{
echo "You are a teenager";
}
?>
b) if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Example
<html>
<body>
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>
c) if...elseif....else Statement
If you've got more than two choices to choose from, you can use the elseif statement.
Syntax
if (expression1)
{
// code is executed if the expression1 evaluates to TRUE
}
elseif (expression2)
{
// code is executed if the expression2 evaluates to TRUE
}
elseif (expression3)
{
// code is executed if the expression3 evaluates to TRUE
}
else
{
// code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a
default choice
}
Example
<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
elseif ($age > 30 && $age < 40)
{
echo "Your age is between 30 and 40!";
}
elseif ($age > 40 && $age < 50)
{
echo "Your age is between 40 and 50!";
}
else
{
echo "Your age is greater than 50!";
}
?>
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed. Use
break to prevent the code from running into the next case automatically. The default
statement is used if no match is found.
Example 1
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
Example 2
<?php
$domain = 'sk';
switch ($domain) {
case 'us':
echo "United States\n";
break;
case 'de':
echo "Germany\n";
break;
case 'sk':
echo "Slovakia\n";
break;
case 'hu':
echo "Hungary\n";
break;
default:
echo "Unknown\n";
break;
}
Looping Statements
Computers often have to do the same task repetitively until some condition is
satisfied. loops are used to execute the same code block for a specified number of times.
The for loop is used when the programmer knows in advance how many times the block
of code should be executed. This is the most common type of loop encountered in almost
every programming language.
Syntax
• initiliation: Mostly used to set a counter (but can be any code to be executed once at the
beginning of the loop)
• condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code to be executed at
the end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions
(separated by commas).
Example
An example where we use the for loop would be:
<html>
<body>
<?php
for ($i=0; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>
Syntax
while (condition)
{
code to be executed;
}
The do...while statement will always execute the block of code once, it will then check
the condition,and repeat the loop while the condition is true.
Its also called an exit controlled loop
Syntax
do
{
code to be executed;
}
while (condition);
example
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
d) foreach Loop
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
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.
The following example demonstrates a loop that will output the values of the
given array ($colors):
example
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) ``
{
echo "$value <br>";
}
?>
</body>
</html>
Arrays
Array is complex variable that enables us to store multiple values in a single variable. We use
this to store related information. An array is a special variable, which can hold more than one
value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
The solution is to create an array! An array can hold many values under a single name, and you
can access the values by referring to an index number.
or
the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota"
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
Associative arrays are arrays that use named keys that you assign to them.
Also known as hash arrays
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>
To loop through and print all the values of an associative array, you could use a
foreach loop, like this:
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep. However, arrays more than three levels deep are hard to
manage for most people.
The dimension of an array indicates the number of indices you need to select an
element.
We can store the data from the table above in a two-dimensional array, like
this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>
Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,descending or
ascending.
The following example sorts the elements of the $numbers array in ascending
numerical order:
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>
The following example sorts the elements of the $numbers array in descending
numerical order:
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>
1. Reducing repetition:
User defined function enables developer to extract commonly used pieces of code as separate
package. These functions help developers avoid redundant work and focus more on the logic
rather than routine things.
2. Easy maintenance:-
Because functions are defined once and used many times, they are used to maintain the code.
During code maintenance if we want to change from values in calculation, we need to change
only in the function. We need not Traverse the whole program for making change in one value.
3. Improves abstraction:
Function forces programmer to think in abstract terms. We need not worry about implementation
of the function. It is enough that we know the function name, number of arguments and return
type of the function.
• Built-in functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform
a specific task
• Creating a Function
• Calling a Function
<?php
// code to be executed
?>
Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and }, the arguments within the function are optional.
invoking function
<?php
….
….
displayShakesphearQuote();
?>
PHP functions are defined with the function keyword following by name of the function.
➢ The name of function should follow the rule for naming variables.
➢ The function code can contain any valid PHP statements, which includes loops conditional
statements and call to other function.
➢ If the function had arguments we have to specify the arguments during invoking
Example
<?php
//define a function
function displayQuote()
echo’some are born great, some achieve greatness and some have greatness through upon them’;.
displayQuote();
?>
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters as you like.
<?php
//define a function
$area=$base*$height*0.5
return $area;
$ta=triangle_area(10,50);
?>
<?php
function greetPerson($name)
greetPerson("Michael");
?>
example
<?php
echo "";
echo "";
echo "";
?>
A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Example:
<html>
<head>
</head>
<body>
<?php
return $sum;
?>
</body>
</html>
Basically, an error is a mistake in a program that may be caused by writing incorrect syntax or
incorrect code. An error message is displayed on your browser containing the filename along
with location, a message describing the error, and the line number in which error has occurred.
There are usually different types of error. In PHP, mainly four types of errors are considered:
2. Fatal Error
3. Warning Error
4. Notice Error
A syntax error is a mistake in the syntax of source code, which can be done by programmers due
to their lack of concern or knowledge. It is also known as Parse error. Compiler is used to catch
the syntax error at compile time.
Fatal Error
A fatal error is another type of error, which is occurs due to the use of undefined function. The
PHP interpreter understands the PHP code but also recognizes the undefined function. This
means that when a function is called without providing its definition, the PHP interpreter
generates a fatal error.
Warning Error
Notice Error
Notice error is same as warning error. When a program contains something wrong, the notice
error occurs. But it allows/continue the execution of the program with a notice error. Notice error
does not prevent the execution of the code. For example - access to undefined variable.