Chapter 6
Front End web development and PHP
1
WHAT IS BACK-END DEVELOPMENT?
web development, there are two critical components: front-end
and back-end development.
While front-end development focuses on the user interface and
user experience
back-end development is responsible for the behind-the-
scenes functionality that powers a website or web application.
The back-end handles tasks such as
processing user input
managing databases
ensuring secure communication between different components
of the application.
2
As a back-end developer, your main responsibilities include:
• Designing, implementing, and maintaining server-side logic and
architecture.
• Collaborating with front-end developers to establish seamless
integration between the front-end and back-end components.
• Managing and optimizing databases to store and retrieve data
efficiently.
• Ensuring the security and privacy of user data by implementing
proper authentication and authorization methods.
• Monitoring, diagnosing, and fixing performance issues and bugs
within the back-end infrastructure.
• Developing and maintaining APIs (Application Programming
Interfaces) for communication between different components or
third-party services.
3
Back-end developers work with various tools and
technologies, such as
programming languages (e.g., Python, Ruby, PHP, Java,
Node.js),
frameworks (e.g., Django, Ruby on Rails, Laravel, Spring,
Express),
databases (e.g., MySQL, PostgreSQL, MongoDB), and
version control systems (e.g., Git).
4
What is PHP?
PHP is a server side scripting language and a powerful tool for
making dynamic and interactive Web pages.
PHP stands for Hypertext Preprocessor
PHP is a server-side scripting language
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix, Oracle, Solid,
PostgresSQL,Generic ODBC, etc.)
PHP is an open source software (OSS)
PHP is free to download and use
5
PHP is whitespace insensitive
What is a PHP File?
PHP files may contain text, HTML tags and scripts
Scripts in a PHP file are executed on the server.
PHP files are returned to the browser as plain HTML
PHP files have a file extension of ".php", ".php3", or ".phtml"
6
Characteristics of PHP
Important characteristics make php's practical nature
possible.
Simplicity
Efficiency
Security
Flexibility
Familiarity
7
Why PHP?
PHP runs on different platforms (Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
PHP is FREE to download from the official PHP resource:
www.php.net
PHP is easy to learn and runs efficiently on the server side 8
To develop and run PHP Web pages three vital components need to be
installed on your 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.
https://httpd.apache.org/download.cgi
Database − PHP will work with virtually all database software, most commonly
used is freely available MySQL database.
https://www.mysql.com/downloads/
9
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.
PHP Syntax
We cannot view the PHP source code by selecting "View source" in the
browser
We only see the output from the PHP file, which is plain HTML.
A PHP scripting block always starts with one of the following tag.
<?php ?>
<? ?>
<% %>
<script type=“php”> </script>
o A PHP file contains HTML tags, and some PHP scripting code.
<html>
<body>
<?php
echo “This is PHP Tag"; 10
?>
</body>
</html>
A PHP scripting block can be placed anywhere in the
document.
Each code line in PHP must end with a semicolon.
The semicolon is a separator and is used to distinguish one set of
instructions from another.
There are two basic statements to output text with PHP: echo
and print.
echo can not be in parenthesis
Print : may or may not be in parenthesis.
11
PHP DATA TYPE
PHP has a total of eight data types which we use to construct
our variables:
Integers: are whole numbers, without a decimal point, like 4195.
Doubles: are floating-point numbers, like 3.14159 or 49.1.
Booleans: have only two possible values either true or false.
NULL: is a special type that only has one value: NULL.
Strings: are sequences of characters, like 'PHP supports string
operations.'
Arrays: are named and indexed collections of other values.
Objects: are instances of programmer-defined classes, which can
package up both other kinds of values and functions that are
specific to the class.
12
Resources: are special variables that hold references to
resources external to PHP (such as database connections).
Variables in PHP
All variables in PHP start with a $ sign symbol. Variables may
contain strings, numbers, or arrays.
<html>
<body>
<?php
$txt=" This is PHP Tag ";
echo $txt;
?>
</body>
</html> 13
VARIABLE NAMING
Rules for naming a variable is:
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
PHP variables can be one of four scope types:
Local variables
Function parameters
Global variables
Static variables
14
PHP ─ CONSTANTS
If you have defined a constant, it can never be changed or
undefined.
There is no need to write a dollar sign ($) before a constant.
To define a constant you have to use define() function and to
retrieve the value of a constant, you have to simply specifying
its name.
constant() function used to retrieve constant variable.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
15
Note that: To concatenate two or more variables together, use the
dot (.) operator:
<html>
<body>
<?php
$txt1=" This is PHP Tag ";
$txt2="1234";
echo $txt1 . " " . $txt2 ;
?>
</body>
16
</html>
Comments in PHP
In PHP, we use // to make a single-line comment or
/* and */ to make a large comment block.
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?> 17
</body>
PHP Operators
Operators are used to operate on values.
This section lists the different operators are used in PHP.
1. Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
18
-- Decrement
2. Assignment Operators
Operator Example Is The Same As
= X=Y X=Y
+= X+=Y X=X+Y
-= X-=Y X=X-Y
*= X*=Y X=X*Y
/= X/=Y X=X/Y
19
%= X%=Y X=X%Y
3. Comparison Operators
Operator Examples
== 5==8 returns False
!= 5!=8 returns True
> 5>8 returns False
< 5<8 returns True
>= 5>=8 returns False
<= 5<=8 returns True 20
4. Logical Operators
Operator Description Example
&& AND x=6
y=3
(x < 10 && y > 1)
returns true
II OR x=6
y=3
(x ==5 II y == 5)
returns false
! NOT x=6
y=3
!(x == y) returns true
21
Control Flow Structure
I. PHP Conditional Statements
Conditional statements in PHP are used to perform different
actions based on different conditions.
when you write code, you want to perform different actions for
different decisions.
22
In PHP we have two conditional statements:
if (...else) statement - use this statement if you want to execute a set
of code when a condition is true (and another if the condition is not
true)
switch statement - use this statement if you want to select one of
many sets of lines to execute
23
A. The If Statement
If you want to execute some code if a condition is true and another
code if a condition is false, use the if....else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
24
CONTROL STRUCTURE
Conditional constructs
If … else
if ( condition1 )
{
statements
}
elseif ( coditon2 )
{
statements
}
elseif( condition3 )
{
…
}
Else
{ 25
statements
}
B. The Switch Statement
If you want to select one of many blocks of code to be executed,
use the Switch statement.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
26
//if expression is different from both label1 and label2;
}
EXAMPLE OF SWITCH STATEMENT
<?php
$x=2;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
27
}
?>
II. PHP Looping
Looping statements in PHP are used to execute the same block of
code a specified number of times
Looping is Very often when you write code, you want the same
block of code to run a number of times. You can use looping
statements in your code to perform this.
In PHP we have the following looping statements:
while - loops through a block of code 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
for - loops through a block of code a specified number of times
for each - loops through a block of code for each element in an
array
28
A. The while Statement
The while statement will execute a block of code if and as long
a condition is true.
<html>
Syntax <body>
while (condition) <?php
code to be executed; $i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body> 29
</html>
B. The do...while Statement
The do...while statement will execute a block of code at least
once - it then will repeat the loop as long as a condition is
true.
<html>
Syntax <body>
do <?php
{ $i=0;
code to be executed; do
{
}
$i++;
while (condition); echo "The number is " . $i . "<br />";
}
while ($i<5);
?>
</body>
30
</html>
C. The for Statement
The for statement is used when you know how many times you
want to execute a statement or a list of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Note: The for statement has three parameters. The first parameter
is for initializing variables, the second parameter holds the
condition, and the third parameter contains any increments
required to implement the loop.
31
D. The for each Statement
Loops over the array given by the parameter. On each loop, the
value of the current element is assigned to $value and the array
pointer is advanced by one - so on the next loop, you'll be
looking at the next element.
Syntax
foreach (array as value)
{
code to be executed;
}
32
Example
The following example demonstrates a loop that will print the
values of the given array:
<html>
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $x)
{
echo "Value: " . $x . "<br />";
}
?>
</body>
</html> 33
Arrays
The most inconvenient thing about a variable is that you can only
store one value at a time.
Arrays are special types that allow variables to overcome this
limitation, so you can store as many values as you want in the
same variable.
For example, instead of having two variables “$number1” and
“$number2”, you could have an array “$numbers” that will hold
both values. 34
array can store two values or two hundred values, without having
to define other variables.
PHP indexes all the values within an array using a number or a
string, so you will know which of the values you’re using.
Working with arrays is easy. You can process each item one after
another, or you could just take one at random.
Each item in an array is commonly referred to as an element.
35
These elements can be accessed directly via their index.
By default, PHP starts indexing elements numerically, from zero,
and increments the element’s index with each new addition, so
keep in mind that the index of the last elements in a numerically
indexed array is always the total number of elements minus one.
Indexing arrays by string can be useful in cases where you need
to store both names and values.
36
There are two ways you can create an array:
with the “array()” function or
directly using the array identifier “[ ]”.
You can use the “array( )” function when you want to assign
multiple elements to an array at a time.
Don’t think that an array can only contain elements of a
certain type (for example, only numbers).
You can have numbers, strings and booleans in the same
array, PHP won’t mind at all.
37
$names = array(“John”, 279, “Selam”, TRUE);
This creates an array called “$names” which holds the specified
elements.
You can access an array element by placing its index between
square brackets, right after the array name.
Not only you can retrieve a value this way, but you can also assign
a value to that element.
print $names[2]; //outputs “Selam”
$names[3] = “Harrison”; //replaces TRUE with “Harrison”
38
Another way to define an array is using the array identifier “[ ]” in
conjunction with the array name.
You can also use this to add new elements in you have already
created an array – either using the “array()” function or the array
identifier.
$names[] = "John";
$names[] = "Mary";
$names[] = "Betty";
$names = array(“Harry”, “Samantha”, “Danny”);
39
There is no need to place any numbers between the square
brackets, PHP takes care of the index number, so you don’t have
to figure out which is the next available slot.
This doesn’t mean that you cannot add numbers, but pay
attention not to skip any of them, because PHP will initialize
only the elements with the index number you specify.
40
PHP Functions
Functions are the most important part of any programming language
Functions are pieces of code that accept values and produce results.
Functions come in handy when you’re writing repetitive code, and you’re
looking to use the same code in other scripts.
A function is a block of code that is not immediately executed, but can be
called by your scripts when needed.
Functions can either be built-in or defined by the user.
41
A. User defined PHP Function
SYNTAX
FUNCTION FUNCTION_NAME()
{
CODE TO BE EXECUTED;
}
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
PHP function guidelines:
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a
number)
42
EXAMPLE
A simple function that writes my name when it is called:
< HTML>
< BODY>
< ?PHP
FUNCTION WRITENAME()
{
ECHO "KAI JIM REFSNES";
}
ECHO "MY NAME IS ";
WRITENAME();
?>
< /BODY> 43
< /HTML>
PHP Functions - Adding parameters
To add more functionality to a function, we can add
parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the
parentheses.
Different functions require different arguments; functions may
ask for multiple arguments (which are separated by commas)
On the other hand, they could also be executed without any
arguments, in which case you only include the parenthesis after
the function name. 44
Example, a function that calculates the values of a purchase
based on the price and
the number of purchased items will require two values.
Let’s assign the result to a variable:
$value = calculate_value($item_price,
$number_of_items); //calls the “calculate_value()”
function with two arguments
45
function calculate_value($price, $items)
{
return ($price * $items); //returns a result
}
$function_name = “calculate_value”;
$function_name(40, 5);
This is identical to:
calculate_value(40, 5);
46
Functions require data to be passed to them, and then return
a result based on that data.
Most functions give you some information after their
completion.
When declaring a function, you must not add a semicolon
after the function statement:
function display_goodbye_message() //no semicolon
here!
print “<h1>Thanks for visiting our 47
web-site</h1>”;
B. PHP Built-in Functions
The real power of PHP comes from its functions.
In PHP - there are more than 700 functions available.
1. PHP Information
The phpinfo() function is used to output PHP information.
This function is useful for trouble shooting, providing the version
of PHP, and how it is configured.
48
Example
<html>
<body>
<?php
// Show all PHP information
phpinfo();
?>
<?php
// Show only the general information
phpinfo(INFO_GENERAL);
?>
</body>
</html>
49
PHP Date() Function
The date() function is used to format a time or a date.
Syntax
string date (date_format[,int timestamp])
This function returns a string formatted according to the
specified format.
PHP Date() - Format the Date
The required format parameter in the date() function
specifies how to format the date/time.
Here are some characters that can be used:
D - Represents the day of the month (01 to 31)
M - Represents a month (01 to 12)
Y - Represents a year (in four digits)
50
Other characters, like"/", ".", or "-" can also be inserted
between the letters to add additional formatting:
EXAMPLE 1.
< ?PHP
ECHO DATE("Y/M/D") . "<BR />";
ECHO DATE("Y.M.D") . "<BR />";
ECHO DATE("Y-M-D");
51
?>
PHP ERROR HANDLING
Error handling is the process of catching errors raised by the
program and then taking appropriate action. Its very simple in
PHP to handle an errors.
Using die() function:: - While writing PHP program, we
should check all possible error condition before going ahead and
take appropriate action when required.
52
EXAMPLE
<?php
if(!file_exists("/tmp/test.txt"))
{
die("File not found");
}
else
{
$file=fopen("/tmp/test.txt","r");
print "Opend file sucessfully";
}
// Test of the code here. 53
?>
PHP FORM
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html><body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" /> 54
</form>
</body></html>
PHP STRING FUNCTIONS
strlen($string): Returns the length of a string.
Example: echo strlen("Hello World"); // Output: 11
str_word_count($string): counting the number of words.
Example: echo str_word_count ("Hello World"); // Output: 2
strrev($string): Reversing a stirng
Example: echo strrev("Hello World"); // Output: dlroW olleH
str_replace($search, $replace, $string): Replaces all
occurrences of a substring with another substring in a given
string. Example: echo str_replace("World", "PHP", "Hello
World"); // Output: Hello PHP
strpos($string, $substring): Returns the position of the first
occurrence of a substring in a string. If the substring is not found,
it returns false. 55
Example: echo strpos("Hello World", "World"); // Output: 6
substr($string, $start, $length): Extracts a portion of a string
starting from a specified position and with a specified length.
Example: echo substr("Hello World", 6); // Output: World
strtolower($string): Converts a string to lowercase.
Example: echo strtolower("Hello World"); // Output: hello
world
strtoupper($string): Converts a string to uppercase.
Example: echo strtoupper("Hello World"); // Output: HELLO
WORLD
ucwords($str): Converting lowercase into title case
Example: echo ucwords("HELLO WORLD "); // Output: Hello
World
str_repeat($str,3): Repeat the string value
Example: echo str_repeat ("Hello World", 2); // Output: Hello
56
World Hello World
The End of Ch-6.
57