PHP Notes
PHP Notes
MINISTRY OF EDUCATION
GLORY ACADEMY
HOURS:120
ACADEMIC YEAR:2022-2023
LU1: APPLY PHP FUNDAMENTALS
PHP stands for Hypertext Preprocessor, that earlier stood for Personal Home Pages. This confuses
many people because the first word of the acronym is the acronym. This type of acronym is called
a recursive acronym.
2. Purpose of PHP
The PHP is a scripting language that allows web developers to create dynamic content that interacts
with databases. PHP is basically used for developing web-based software applications.
PHP is often used to build dynamic web pages. A dynamic web page is one where each visitor to
the web gets a customized page that can look different than how the site looks to another visitor.
This is in contrast to static web pages which provide the same contents to each visitor.
3.PHP files
PHP files have the. php extension can contain text, HTML tags and scripts (script is a set of
programming instructions that is interpreted at runtime.). These files are processed by a remote
server and are then returned to the user's web browser as plain HTML.
1|Page
A PHP script can be placed anywhere in the document and It starts with
<?php
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
You can different the scripting and programming languages on the following elements:
1.Server-side processes
The scripting languages needs the server for being processed whereas the programming
languages does not require the server for processing.
Compiler is a translator which takes high level language, and produces an output of low level
language i.e. machine or assembly language. The compiler scans the whole program in one go.
For programming languages, the code has to be compiled before it can be executed. This means
that the compiler is needed before the execution.
For scripting languages, the code has to be interpreted before it can be executed. This means that
the interpreter is needed before the execution.
Generally, compiled programs run faster than interpreted programs because they are first converted
native machine code. Also, compilers read and analyze the code only once, and report the errors
collectively that the code might have but the interpreter will read and analyze the code statements
each time it meets them and halts at that very instance if there is some error.
3.Inside HTML files
The scripting languages run inside another program (like PHP runs inside HTML file). It is usually
embedded into other software environments whereas the programming languages run independent
of a parent program.
2|Page
The scripting languages require a host means that they need the servers which are used for
processing the scripts before the output whereas the programming languages does not require a
host. They are self-executable.
LO 1.2 Describe PHP Syntax, data types, variables, operators and arrays
Variables are used to store a value that can change during the program execution.
A variable starts with the $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($option and $OPTION are two different variables)
The assignment operator (=) used to assign value to a variable.
PHP supports total eight primitive data types: Integer, Floating point number or Float, string,
booleans, array, object, resource and null. These data types are used to construct variables.
1.Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers can be
specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 -
prefixed with 0) notation, optionally preceded by a sign (- or +).
3|Page
Example:
<?php
$a = 123; // decimal number
echo $a;
echo "<br>";
<?php
$var = 0b11111111;
echo $var;
?>
2.Strings
Strings are sequences of characters, where every character is the same as a byte.
A string can hold letters, numbers, and special characters. The simplest way to specify a string is
to enclose it in single quotes (e.g. 'Hello world!'), however you can also use double quotes ("Hello
world!").
Example:
<?php
$a = 'Hello world!';
echo $a;
echo "<br>";
$b = "Hello world!";
echo $b;
echo "<br>";
4|Page
echo $c;
?>
$b = 10.2e3;
echo $b;
echo "<br>";
$c = 4E-10;
echo $c;
?>
4.Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
Example
<?php
// Assign the value TRUE to a variable
$show_error = true;
echo $show_error;
?>
5.Arrays
An array is a variable that can hold more than one value at a time. It is useful to aggregate a
series of related items together, for example a set of country or city names.
An array is formally defined as an indexed collection of data values. Each index (also known as
the key) of an array is unique and references a corresponding value.
5|Page
Example
<?php
// Define array
var_dump($cities);// array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8)
"New York" }
?>
6.Objects
An object is a data type that not only allows storing data but also information on, how to process
that data. An object is a specific instance of a class which serve as templates for objects. Objects
are created based on this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class. Every object
instance is completely independent, with its own properties and methods, and can thus be
manipulated independently of other objects of the same class.
Here's a simple example of a class definition followed by the object creation.
Example
<?php
class SayHello{
function hello()
{
echo "Hello World";
}
}
$obj=new SayHello;
$obj->hello();
?>
7.Null
The special Null value is used to represent empty variables in PHP. A variable of type Null is a
variable without any data. Null is the only possible value of type null.
6|Page
Example
<?php
$a=NULL;
echo $a;
echo "<br>";
$b="Hello World!";
$b=NULL;
echo $b;
?>
When a variable is created without a value in PHP like $var; it is automatically assigned a value
of null. Many novice PHP developers mistakenly considered both $var1 = NULL; and $var2 =
""; are same, but this is not true. Both variables are different, the $var1 has null value
while $var2 indicates no value assigned to it.
8.Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database connections.
Example
<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";
1.2.3 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 of letters, numbers, or underscores. If you have defined a constant, it can never be
changed or undefined.
7|Page
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. Unlike with variables, you do not need to have a constant
with a $. You can also use the function constant() to read a constant's value if you wish to obtain
the constant's name dynamically.
PHP introduced a keyword const to create a constant. The constant defined using const keyword
are case-sensitive.
Example1:
<?php
define("MINSIZE", 50);
echo MINSIZE;
?>
Example2:
<?php
define("MESSAGE","Hello PHP",true);
echo MESSAGE, "</br>";
echo message;
?>
Example 3:
<?php
echo MESSAGE,"<br>";
?>
8|Page
1.2.4 Operators
PHP language supports following type of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Let’s have a look on all operators one by one.
i)Arithmetic Operators
There are following arithmetic operators supported by PHP language. Assume variable A holds
4 and variable B holds 2 then
9|Page
-- Decrement Decrement operator, decreases integer value $A-- will give 3
by one
ii)Comparison Operators
There are following comparison operators supported by PHP language. Assume variable A holds
10 and variable B holds 20 then
> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.
10 | P a g e
iii)Logical Operators
There are following logical operators supported by PHP language. Assume variable A holds 10
and variable B holds 20 then
and Called Logical AND operator. If both the operands are true (A and B) is
then condition becomes true. true.
&& Called Logical AND operator. If both the operands are non- (A && B) is
zero then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state !(A && B)
of its operand. If a condition is true then Logical NOT operator is false
will make false.
iv)Assignment Operators
There are following assignment operators supported by PHP language
11 | P a g e
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to
operand from the left operand and assign the result to C=C-A
left operand
v)Conditional operator
There is one more operator called conditional operator. This first evaluates an expression for a
true or false value and then execute one of the two given statements depending upon the result of
the evaluation. The conditional operator has this syntax
Example
<?php
$A=45;
$B=20;
12 | P a g e
$result=($A>$B)?"The value of A is greater than the value of B":"The value of B is greater than
the value of A";
echo $result;
?>
1.2.5 Expressions
An expression can be evaluated to produce a value. The simplest expressions are literal values and
variables. A literal value evaluates to itself, while a variable evaluates to the value stored in the
variable. More complex expressions can be formed using simple expressions and operators.
Expressions are the most important building blocks of PHP. In PHP, almost anything you write is
an expression. The simplest yet most accurate way to define an expression is "anything that has a
value".
The most basic forms of expressions are constants and variables. When you type "$a = 5", you're
assigning '5' into $a.
1.2.6 Arrays
An array is a data structure that stores one or more similar type of values in a single value. For
example, if you want to store 100 numbers then instead of defining 100 variables it’s easy to
define an array of 100 lengths.
There are three different kind of arrays and each array value is accessed using an ID which is
called array index.
1.Numeric array /Indexed array − An array with a numeric index. Values are stored and
accessed in linear fashion.
Example:
<html>
<body>
<?php
/* First method to create array */
13 | P a g e
{
echo "Value is $value <br />";
}
/* Second method to create array */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
Example:
<html>
<body>
<?php
$salaries = array("Paul" => 2000, "Anitha" => 1000, "Divin" => 500);
14 | P a g e
$salaries['Paul'] = "high";
$salaries['Anitha'] = "medium";
$salaries['Divin'] = "low";
?></body>
</html>
3.Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices.
A multi-dimensional array each element in the main array can also be an array. And each element
in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed
using multiple index.
Example
In this example we create a two-dimensional array to store marks of three students in three
subjects.
<?php
$marks = array( "Paul" => array ("physics" => 35,"maths" => 30,"chemistry" => 39
),"Anitha" => array ( "physics" => 30, "maths" => 32,"chemistry" => 29), "Divin" => array
("physics" => 31, "maths" => 22, "chemistry" => 39 ) );
15 | P a g e
?>
</body>
</html>
The output:
A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose
is to be read by someone who is looking at the code.
2.Types of comments
PHP has two types. The first type we will discuss is the single line comment. The single line
comment tells the interpreter to ignore everything that occurs on that line to the right of the
comment. To do a single line comment type "//" or "#" and all text to the right will be ignored by
PHP interpreter.
The second type is multi-line comment can be used to comment out large blocks of code or
writing multiple line comments. The multiple line comment begins with " /* " and ends with " */
".
To use the PHP comments in php you can // or # for single line comments.
Here, there is example that shows how you can use single line comment
<?php
16 | P a g e
echo "Hello World!"; // This will print out Hello World!
?>
Hello World!
You can't see my PHP comments!
To use the PHP comments in php you can /* */ for multiple line comments.
Here, there is example that shows how you can use multiple line comment
<?php
/* This echo statement will print out my message to the
the place in which I reside on. */
echo "Hello World!";
?>
17 | P a g e
LU 2 IMPLEMENT PHP LOGIC
LO2.1: Use PHP control structures
2.1.1 Application of program flow control
1. Conditional statements
PHP lets programmers evaluate different conditions during of a program and take decisions based
on whether these conditions evaluate to true or false.
These conditions, and the actions associated with them, are expressed by means of a programming
construct called a conditional statement.
A.if Statement
The if Statement is the simplest conditional statements. In if statements output will appear when
only condition must be true.
If statement works much like the English language statement, “if X happens, then do Y.”
if (condition) {
code to be executed if condition is true;
}
Example:
<?php
$t = date("H");
Exercises:
18 | P a g e
B. if-else Statement
The if statement is quite basic because in If statement output will display when condition must be
true, if the condition is false it display nothing(blank) as the message.
But if-else statements allows you to display output in both the condition (if condition is true
display some message otherwise display other message).
In English, this statement would read, “if X happens, do Y; otherwise do Z”.
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise.
Example:
<?php
$t = date("H");
The if-elseif-else statement lets you chain together multiple if-else statements, thus allowing the
programmer to define actions for more than just two possible outcomes.
19 | P a g e
The syntax is:
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!"
Example:
<?php
$t = date("H");
2. Write a php program to print related day name according to inputted number (1 – 7).
D.Switch statement
It only executes a single block of code depending on the value of the condition.
If no condition has been met, then the default block of code is executed.
20 | P a g e
<?php
switch(condition){
case value:
//block of code to be executed
break;
case value2:
//block of code to be executed
break;
default:
//default block code
break;
}
?>
Example:
<?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":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Exercise:
1. Enter first number, second number and choice arithmetic operator, make calculation.
2.Iterative statements
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
21 | P a g e
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.
i.For
The for loop is used when you know in advance how many times the script should run.
Syntax
Example: Write a PHP program for printing the first five natural numbers
<?php
?>
Exercises:
ii.while
22 | P a g e
Syntax
while (condition)
code to be executed;
Example: Write a PHP program for printing the first five natural numbers
<?php
$i=1;
while($i<=5)
{
echo "The number is ". $i . "<br>";
$i++;
}
?>
Exercises:
iii.Do while
The do…while Loop executes the statement once and then check the condition.
Syntax
do
{
code to be executed;
}
while (condition);
Example: Write a PHP program for printing the first five natural numbers
<?php
$i=1;
do
23 | P a g e
{
echo "The number is " . $i . "<br>";
$i++;
}
while ($i<=5);
?>
Exercise:
1.Write a program to display table of given number.
iv). Foreach
You can define two parameters inside foreach separated through “as” keyword.
First parameter must be existing array name which elements or key you want to display.
At the Position of 2nd parameter, could define two variables: One for key(index)
and another for value.
If you define only one variable at the position of 2nd parameter, it contains arrays value (By default
display array value).
Syntax
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) – so on the next loop iteration, you’ll be looking at the next array
value.
The following example demonstrates a loop that will print the values of the given array.
Example 1:
<?php
$person=array("alex", "simon","ravi");
foreach ($person as $val)
{
24 | P a g e
echo $val."<br/>";
}
?>
Example 2:
<?php
$marks = array(
foreach($marks as $mark) {
echo $mark['Maths']. " ".$mark['Physics']." ".$mark['Biology']."<br>";
}
?>
25 | P a g e
Examples:
2.User-defined functions
Syntax
function functionName() {
code to be executed;
}
A function name must start with a letter or an underscore. Function names are not case-sensitive.
Thus, the concept of "void" functions does not apply to PHP. You can specify the return value of
your function by using the return keyword.
Examples:
1. <?php
function add($a,$b){
$total = $a + $b;
return $total; //Function return, No output is shown
}
2.<?php
function hello(){
return "Hello World"; // No output is shown
}
$txt = hello(); // Assigns the return value "Hello World" to $txt
echo hello(); // Direct Displays "Hello World"
1
https://www.w3schools.com/php/php_functions.asp 12/03/2020
26 | P a g e
?>
Some of the most useful PHP functions are string manipulation functions. As the name suggests
they manipulate strings.
strlen
Example:
<?php
$name = "Matthew";
echo strlen($name); // 7
?>
substr
The substr() function is used to return a substring or part of a string. This function has 3
parameters which you can pass along.
If $start is negative, the returned string will start at the start'th character from the end of string.
If $string is less than $start characters long, FALSE will be returned.
Note: If you don’t provide a $length parameter, this function will just return the remainder of the
string starting from the $start parameter.
Example:
<?php
$name = "Matthew";
echo substr($name, 0, 5); // Matth
27 | P a g e
echo substr($name, 2); // tthew
echo substr($name, 7,2);//No output because of 7 is grater than 6
echo substr($name,-7,2);//Ma
?>
Explanation
M a t t h e w
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
<?php
$name = "Matthew ";
echo strtoupper($name); // MATTHEW
echo strtolower($name); // matthew
?>
Strrev
Syntax
strrev ( string )
Example:
<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>
strpos
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string
or a string inside another string. The function returns an integer value which is the index of the
28 | P a g e
first occurrence of the string. The upper-case and lower-case characters are treated differently as
the function is case-sensitive.
Syntax: strpos(string,find,start)
Example1:
<?php
$name = "Matthew ";
echo strpos($name, "M"); // 0
echo strpos($name, "hew"); // 4
echo strpos($name, "m"); // false
?>
Example2:
<?php
Echo strops("strops in php","php");//10
?>
htmlentities()
The htmlentities() function converts characters to HTML entities.
Example:
<?php
$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a><br>';
echo htmlentities($str);
?>
Trim
The trim() function removes whitespace and other predefined characters from both sides of a
string.
Related functions:
ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a
string
Example1:
Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"):
29 | P a g e
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
printf
The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This
function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is
inserted, etc.
Note: If there are more % signs than arguments, you must use placeholders. A placeholder is
inserted after the % sign, and consists of the argument- number and "\$".
%% - Returns a percent sign, %b - Binary number, %c - The character according to the ASCII
value, %d - Signed decimal number (negative, zero or positive), %e - Scientific notation using a
lowercase (e.g. 1.2e+2), %E - Scientific notation using a uppercase (e.g. 1.2E+2), %u - Unsigned
decimal number (equal to or greater than zero), %f - Floating-point number (local settings
aware), %o - Octal number, %s – String, %x - Hexadecimal number (lowercase letters),%X -
Hexadecimal number (uppercase letters).
These are placed between the % and the letter (example %.2f).
Example1:
<?php
$number = 9;
$str = "Beijing";
printf("There are %u million bicycles in %s.",$number,$str);
?>
Example2:
<?php
$number = 123;
printf("%f",$number);
?>
Example3:
30 | P a g e
<?php
$number = 123;
printf("With 2 decimals: %1\$.2f
<br>With no decimals: %1\$u",$number);
?>
str_word_count()
The str_word_count() function counts the number of words in a string.
Example 1:
<?php
// Count the number of words found in the string "Hello World!"
echo str_word_count("Hello world!");//2
?>
Example 2:
<?php
// Return an array with the words from the string
print_r(str_word_count("Hello world!",1));// Array ( [0] => Hello [1] => world )
?>
Example 3:
<?php
// Return an array where the key is the position of the word in the string, and value is the actual
word
print_r(str_word_count("Hello world!",2));// Array ( [0] => Hello [6] => world )
?>
Exercises
<?php
$name ="Matthew";
echo strlen($name);
echo"<br>";
echo substr($name,3,4);
echo"<br>";
echo substr($name,4,1);
echo"<br>";
echo substr($name,-2,3);
echo"<br>";
31 | P a g e
echo substr($name,-3,2);
echo"<br>";
echo substr($name,-5,4);
echo"<br>";
echo substr($name,8,4);
?>
<?php
$schoolName="GLORY ACADEMY";
echo strtoupper($schoolName);
echo "<br>";
echo strtolower($schoolName);
?>
<?php
$name2="Level 5";
echo strrev($name2);
echo"<br>";
$name="Matthew";
echo strpos($name,"tt");
echo"<br>";
echo strpos($name,"at",1);
echo"<br>";
echo strpos($name,"hew",3);
echo"<br>";
echo strpos($name,"hew",4);
echo"<br>";
echo strpos($name,"hew");
echo"<br>";
echo strpos($name,"T");
?>
32 | P a g e
LO2.3: Implement PHP File processing
1.Image formats
PHP is not limited to creating just HTML output. It can also be used to create and manipulate
image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP (wireless
Bitmap), and XPM(X PixMap). Even more conveniently, PHP can output image streams directly
to a browser. You will need to compile PHP with the GD (Graphics draw) library of image
functions for this to work. GD and PHP may also require other libraries, depending on which
image formats you want to work with.
You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF(Shockwave
Fash), TIFF and JPEG2000 images.
A.is_file
The is_file() function checks whether the specified filename is a regular file.
Syntax:
is_file(file)
Program 1:
<?php
$myfile = "gfg.txt"; // checking whether the file is a regular file or not
if (is_file($myfile)) {
echo ("$myfile: regular file!");
} else {
echo ("$myfile: not a regular file!");
}
?>
Output:
gfg.txt: regular file!
B. file_exists
33 | P a g e
Examples:
<?php
$file = 'C:/xampp/htdocs/L52022/welcome.docx';
if (file_exists($file)) {
echo "The file $file exists";
}else {
echo "The file $file does not exists";
}
?>
C.fopen
If fopen() fails, it returns FALSE and an error on failure. You can hide the error output by adding
an '@' in front of the function name.
Syntax
fopen(filename,mode,include_path,context)
Parameter Description
filename Required. Specifies the file or URL to open
mode
Required. Specifies the type of access you require to the file/stream.
Possible values:
"x+" (Read/Write. Creates a new file. Returns FALSE and an error if file
already exists)
include_path Optional. Set this parameter to '1' if you want to search for the file in the
include_path (in php.ini) as well
34 | P a g e
context Optional. Specifies the context of the file handle. Context is a set of options
that can modify the behavior of a stream
Example 1:
<?php
$myfile = fopen("level5.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("level5.txt"));
fclose($myfile);
?>
Example 2:
<?php
$file = fopen("welcome.txt", "r");
fclose($file);
?>
D.fwrite
The function will stop at the end of the file (EOF) or when it reaches the specified length,
whichever comes first.
Syntax
Example
<?php
$file = fopen("welcome.txt","w+");
echo fwrite($file,"Level 5 Software Development");//28(in bytes=number of characters+spaces)
fclose($file);
?>
35 | P a g e
E.fclose
Syntax: fclose(file)
Example 1:
<?php
$file = fopen("level5.txt","r");
//some code to be executed
fclose($file);
?>
F.fgets
The fgets() function stops returning on a new line, at the specified length, or at end of file(EOF),
whichever comes first.
Syntax: fgets(file,length)
Example 1:
<?php
//Read one line from the open file
$file = fopen("level5.txt","r");
echo fgets($file);
fclose($file);
?>
Example 2:
<?php
$file = fopen("level5.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
}
36 | P a g e
fclose($file);
?>
G.fgetss
The fgetss() function returns a line, with HTML and PHP tags removed, from an open file.
The fgetss() function stops returning on a new line, at the specified length, or at EOF, whichever
comes first.
Syntax
fgetss(file,length,tags)
Parameter Description
file Required. Specifies the file to check
length
Optional. Specifies the number of bytes to
read. Default is 1024 bytes.
H.copy
37 | P a g e
Syntax: copy(from_file,to_file)
Example
<?php
echo copy("source.txt","target.txt");
?>
I.Unlink
Syntax: unlink(filename,context)
Example
<?php
$file = "test.txt";
if (!unlink($file))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $file");
}
?>
J.file_get_contents
This function is the preferred way to read the contents of a file into a string. Because it will use
memory mapping techniques, if this is supported by the server, to enhance performance.
Syntax
file_get_contents(path, include_path,context,start,max_length)
Parameter Description
path Required. Specifies the file to read
38 | P a g e
include_path Optional. Set this parameter to '1' if you want
to search for the file in the include_path (in
php.ini) as well
context Optional. Specifies the context of the file
handle. Context is a set of options that can
modify the behavior of a stream. Can be
skipped by using NULL.
start Optional. Specifies where in the file to start
reading. This parameter was added in PHP 5.1
max_length Optional. Specifies how many bytes to read.
This parameter was added in PHP 5.1
Tip: This function is binary-safe (meaning that both binary data, like images, and character data
can be written with this function).
Example 1:
<?php
echo file_get_contents("level5.txt");
?>
Example 2:
<?php
// Reading 100 bytes starting from
// the 0th character from welcome2.txt
$text = file_get_contents('welcome2.txt', false, NULL, 0, 100);
echo $text;
?>
Exercises
1.Write a PHP program that checks if bumba.txt is regular file.
2.Give the syntax of the following functions:
a) file_exists()
b) copy()
3.Write a PHP that opens and displays the contents of file called welcome.txt.
4.Write a PHP program that opens and displays the first line of content in file called imihigo.txt
39 | P a g e
5.Write a PHP program that uses gets function to display the output of this HTML file called
test.html.
test.html
<!doctype html>
<html>
<head><title>Getss example</title>
</head>
<body>
<h1>List of items</h1>
<ol>
<li>Laptop</li>
<li>Desktop</li>
</ol>
<p><strong>Good Luck!!</strong></p>
</body>
</html>
40 | P a g e
LO2.4: Handle Errors and Exceptions
2.4.1 Description of program error types
1.Syntax errors
Syntax Error (Parse Error) occurs if there is a syntax mistake in the script; the output is
Parse error. A parse error stops the execution of the script. There are many reasons for the
occurrence of parse errors in PHP. The common reasons for parse errors are as follows:
1. Unclosed quotes
2. Missing or Extra parentheses
3. Unclosed braces
4. Missing semicolon
Example:
<?php
echo "Cat";
echo "Dog"
echo "Lion";
?>
2.Logical errors
The logical or semantic error is a fault in program design like the order of instruction. They may
cause a problem to respond incorrectly to the user or crash completely.
If there is any logical error in code, the PHP script will compile and run successfully and the
computer will not generate any error message. But does not do the right thing.
PHP code does not print last message. An infinite loop was entered.
Example:
<?php
for($i=1;;$i++)
{
echo $i;
}
?>
41 | P a g e
3.Run time errors
Runtime error refers to the error that occurs during execution of the code, which are not usually
programming error, but caused by factors outside PHP script itself, such as database calls or disk
or network operation.
Example:
The mysqli_connect () function falls, because the username specified was accidently deleted by
the MySQL administrator.
1.die function
die( ) function is used to display a message and exit the script. It may be used to print alternate
message. Instead of showing error it will show the user-friendly message.
Example:
<?php
$con= mysqli_connect("localhost","root","") or die('connection not found');
?>
In the above example if the connection with database is not established due to some error the die
function shows the message “connection not found”.
Creating a custom error handler in PHP is quite simple. Create a function that can be called when
an error has been occurred in PHP.
Syntax:
42 | P a g e
Parameter Description
error_level Required. Specifies the error report level for
the user-defined error. Must be a value
number. Example: 1(E_ERROR): A fatal run-
time error. Execution of the script is
stopped,2(E_WARNING): A non-fatal run-
time error. Execution of the script is not
stopped, 8(E_NOTICE): A run-time notice.
The script found something that might be an
error, but could also happen when running a
script normally,…
error_message Required. Specifies the error message for the
user-defined error
error_file Optional. Specifies the filename in which the
error occurred
error_line Optional. Specifies the line number in which
the error occurred
error_context Optional. Specifies an array containing every
variable, and their values, in use when the
error occurred
Example:
<?php
// Creates my error function which prints message to user
function myerror($error_no, $error_msg,$error_file,$error_line,$error_context)
{
echo "[$error_no] <br> $error_msg <br>$error_file ";
echo "<br> $error_line";
echo "<br> $error_context";
// Setting set_error_handler
set_error_handler("myerror");
$a = 10;
$b = 0;
43 | P a g e
// This will generate error
echo($a / $b);
?>
Output:
[2]
Division by zero
C:\xampp\htdocs\sfd50119\customerror.php
20
Notice: Array to string conversion in C:\xampp\htdocs\sfd50119\customerror.php on line 7
Array
PHP try and catch are the blocks with the feature of exception handling, which contain the code
to handle exceptions. There is one more important keyword used with the try-catch block
is throw. The throw is a keyword that is used to throw an exception.
try {
// code
The try block is the one to use where you suspect that your code may generate an exception. You
should always wrap such code using try and catch.
44 | P a g e
Example:
Let's assume that you've built an application which loads the application connection to mysql
server from the connection.php file. Now, it's essential that the connection.php file is present
when your application is connected to mysql server. Thus, your application can't run if
the connection.php file is not present. So this is the perfect use case to throw an exception and
let the user know they need to fix the issue.
<?php
try {
$file = "connection.php";
if (!file_exists($file))
{
throw new Exception("Connection file not found.");
}
Complete program
<!DOCTYPE html>
<head><title>Data presentation in HTML table</title>
</head>
<body>
<?php
try {
$file = "connection.php";
if (!file_exists($file))
{
throw new Exception("Connection file not found.");
}
include('connection.php');
45 | P a g e
$select='select * from Modules';
$query=mysqli_query($con,$select);
echo"<center><table border='1'>
<caption><h2><u>LIST OF MODULES</u></h2></caption>
<tr><th>MID</th><th>MODULE CODE</th><th>MODULE NAME</th></tr>";
while($record=mysqli_fetch_array($query))
{
echo"<tr>";
echo"<td>".$record['MId']."</td>";
echo"<td>".$record['ModuleCode']."</td>";
echo"<td>".$record['ModuleName']."</td>";
echo"<tr>";
}
echo"</table></center>";
}
?>
<body>
</html>
46 | P a g e
LU 3 PERFORM PHP MYSQL DATABASE INTERACTIONS
1.Connection object
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
2.mysqli_connect
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
3.PDO
The PHP Data Objects (PDO) defines a lightweight interface for accessing databases in PHP.
47 | P a g e
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Note: In the PDO example above we have also specified a database (myDB). PDO require a
valid database to connect to. If no database is specified, an exception is thrown.
A great benefit of PDO is that it has an exception class to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the script stops executing
and flows directly to the first catch(){ } block.
Example 1:
<?php
$dbHost="localhost";
$dbName="isoko";
$dbUser="root";
$dbPassword="";
try{
$dbConn= new PDO("mysql:host=$dbHost;dbname=$dbName",$dbUser,$dbPassword);
Echo "Successfully connected with $dbName database";
} catch(Exception $e){
Echo "Connection failed" . $e->getMessage();
}
$dbConn=null;
?>
Example 2:
<?php
48 | P a g e
$dbHost="localhost";
$dbName="isoko";
$dbUser="root";
$dbPassword="";
try{
$dbConn= new PDO("mysql:host=$dbHost;dbname=$dbName",$dbUser,$dbPassword);
$stmt = $dbConn->prepare("SELECT * FROM products");
$stmt->execute();
$users = $stmt->fetchAll();
if($users)
{
echo"<h3></u>LIST OF CUSTMERS</u></h3>";
echo"<table border=1 cellspacing=0>
<tr><th>ID</th><th>Name</th><th> Category ID</th></tr>";
foreach($users as $user)
{
echo"<tr>";
echo"<td>";
echo $user['id'];
echo"</td>";
echo"<td>";
echo $user['name'];
echo"</td>";
echo"<td>";
echo $user['category_id'];
echo"</td>";
echo"</tr><br>";
}
echo"</table>";
}
else
{
echo "No Records found";
}
}
catch(Exception $e){
Echo "Connection failed" . $e->getMessage();
}
$dbConn=null;
?>
3.2.2 Application database access methods
1.mysqli_select_db
49 | P a g e
The mysqli_select_db() function is used to change the default database for the connection.
Syntax: mysqli_select_db(connection,dbname);
Example:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
mysqli_select_db($con,"test");
The mysqli_query() function accepts a string value representing a query as one of the
parameters and, executes the given query on the database.
Syntax: mysqli_query(connection,query,resultmode);
Parameter Description
connection Required. Specifies the MySQL connection to
use
query Required. Specifies the query string
resultmode Optional. A constant. Either:
Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
mysqli_query($con,"INSERT INTO
users(userFirstname,userLastname,Username,userPassword)
VALUES('Alice','UWAYO', 'Ace1', 'Alice1231')");
?>
3.mysqli_num_rows
50 | P a g e
The mysqli_num_rows() function returns the number of rows in a result set.
Syntax:
mysqli_num_rows(result);
Parameter Description
result Required. Specifies a result set identifier
returned by mysqli_query().
Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="select * from users";
$result=mysqli_query($con,$sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.<br>",$rowcount);
?>
4.mysqli_fetch_array
The mysqli_fetch_array() function fetches a result row as an associative array, a numeric array,
or both.
Syntax: mysqli_fetch_array(result,resulttype);
Parameter Description
result Required. Specifies a result set identifier
returned by mysqli_query()
resulttype
Optional. Specifies what type of array that
should be produced. Can be one of the
following values:
MYSQLI_ASSOC
MYSQLI_NUM
51 | P a g e
MYSQLI_BOTH
Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="SELECT * FROM modules where moduleId=1";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo $row['moduleId']." ".$row['moduleCode']." ".$row['moduleName']."<br>";
}
?>
5.mysqli_close
Syntax
mysqli_close(connection);
Parameter Description
connection Required. Specifies the MySQL connection to
close
Example
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
mysqli_close($con);
?>
52 | P a g e
LO 3.2 Implement database CRUD Operations
3.2.1 Manipulation of database table records
1. Insert record
To insert record in database you need to use INSERT INTO statement. It is possible to write the
INSERT INTO statement in two ways. The first way specifies both the column names and the
values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3,
...);
If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as the
columns in the table. The INSERT INTO syntax would be as follows:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="INSERT INTO users(userFirstname,userLastname,Username,userPassword)
VALUES('Pierre','KAMANA', 'Pierre', 'Pierre23')";
$insertquery=mysqli_query($con,$sql);
if($insertquery==true)
{
echo"Record is inserted successfully!";
}
else
{
echo"Record is not inserted!";
}
mysqli_close($con);
?>
2.Retrieve records
SELECT Syntax
SELECT column1, column2, ... FROM table_name;
53 | P a g e
Here, column1, column2, ... are the field names of the table you want to select data from. If you
want to select all the fields available in the table, use the following syntax:
To retrieve one record from the database you need to use a primary field value as the condition
with the SELECT statement.
Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="SELECT * FROM modules where moduleId=4";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo $row['moduleId']." ".$row['moduleCode']." ".$row['moduleName']."<br>";
}
mysqli_close($con);
?>
4.Update record
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
54 | P a g e
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE
statement. The WHERE clause specifies which record(s) that should be updated. If you omit the
WHERE clause, all records in the table will be updated!
Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="update users set userFirstname='John' where userid=1 ";
$updatequery=mysqli_query($con,$sql);
if($updatequery==true)
{
echo"Record is updated successfully!";
}
else
{
echo"Record is not updated!";
}
mysqli_close($con);
?>
5.Delete record
Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause,
all records in the table will be deleted.
Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="delete from users where userid=7";
$deletequery=mysqli_query($con,$sql);
if($deletequery==true)
{
echo"Record is deleted successfully!";
}
else
{
55 | P a g e
echo"Record is not deleted!";
}
mysqli_close($con);
?>
<?php
if(isset($_POST['export']))
{
$host="localhost";
$username="root";
$password="";
$databasename="gsbms";
$data="";
$connect=mysqli_connect($host,$username,$password);
$db=mysqli_select_db($connect,$databasename);
56 | P a g e
$select = mysqli_query($connect,"SELECT * FROM users");
while($row=mysqli_fetch_array($select))
{
$data.=$row['userid'].",";
$data.=$row['userFirstname'].",";
$data.=$row['userLastname'].",";
$data.=$row['Username'].",";
$data.=$row['userPassword']."\n";
}
echo $data;
header("Content-Disposition: attachment; filename=mysql_to_excel.csv");
exit();
}
?>
57 | P a g e
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
if(isset($_POST["submit_file"]))
{
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
{
$name = $csv[0];
$age = $csv[1];
$country = $csv[2];
mysqli_query($con,"INSERT INTO employees VALUES ('$name','$age','$country')");
}
}
?>
LO 3.3 Manage sessions and cookies
1.Importance of cookies
An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie)
is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookies were designed to be a reliable mechanism for websites to remember stateful information
or to record the user's browsing activity (including clicking particular buttons, logging in, or
recording which pages were visited in the past). They can also be used to remember arbitrary
pieces of information that the user previously entered into form fields such as names, addresses,
passwords, and credit card numbers. A cookie is often used to identify a user.
Once a cookie has been set, all page’s requests that follow return the cookie name and value.
58 | P a g e
Types of Cookies: Session based cookie which expires at the end of session and Persistent
cookies which are written on hard disk.
Cookies can have an expiry time, if it is not set, then the cookie expires when the browser is closed.
3.Create cookies
<?php
?>
HERE,
expiry_time is optional; it can be used to set the expiry time for the cookie such as 1 hour.
The time is set using the PHP time() functions plus or minus a number of seconds greater
than 0 i.e. time() + 3600 for 1 hour.
cookie_path is optional; it can be used to set the cookie path on the server. The forward
slash “/” means that the cookie will be made available on the entire domain. Sub directories
limit the cookie access to the subdomain.
secure is optional, the default is false. It is used to determine whether the cookie is sent via
https if it is set to true or http if it is set to false.
Httponly is optional. If it is set to true, then only client side scripting languages
i.e.JavaScript cannot access them.
59 | P a g e
Note: the php setcookie function must be executed before the HTML opening tag.
We will create a basic program that allows us to store the user name in a cookie that expires after
60 seconds.
The code below shows the implementation of the above example “cookies.php”.
<?php
setcookie("user_name", "minageni", time()+ 60,'/'); // expires after 60 seconds
echo 'The cookie has been set for 60 seconds';
?>
Output:
<?php
print_r($_COOKIE); //output the contents of the cookie array variable
?>
Output:
5.Delete cookies
If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that
has already passed.
<?php
60 | P a g e
?>
3.3.2 Introduction and use of sessions
1.Importance of sessions
A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file
called session.save_path. Before using any session variable make sure you have setup this path.
A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.
3.Create sessions
A PHP session is easily started by making a call to the session_start()function. This function first
checks if a session is already started and if none is started then it starts one. It is recommended to
put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[ ]. These variables can be
accessed during lifetime of a session.
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
61 | P a g e
$_SESSION["schoolname"] = "GLORY ACADEMY";
$_SESSION["level"] = "five";
?> </body>
</html>
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single
session variable then you can use unset() function to unset a session variable.
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
session_destroy();
?>
When you embed PHP code in an HTML file, you need to use the .php file extension for that file,
so that your web server knows to send the file to PHP for processing.
The PHP language statements are enclosed in PHP tags with the following form:<?php ?>
Example
<!doctype html>
62 | P a g e
<html>
<body>
<?php
2.POST method
It appends form-data to the body of the HTTP request in such a way that data is not shown in
the URL. This method does not have any restrictions on data size to be sent. Submissions by form
with POST cannot be bookmarked. This method can be used to send ASCII(American Standard
Code for Information Interchange) as well as binary data like image and word documents. Data
sent by the POST method goes through HTTP header so security depends on the HTTP protocol.
You have to know that your information is secure by using secure HTTP. This method is a little
safer than GET because the parameters are not stored in browser history or in web server logs. It
also provides $_POST associative array to access all the sent information using the POST method.
<?php
$_POST['variable_name'];
?>
3. GET method
It appends form-data to the URL in name/ value pairs. The length of the URL is limited by 2048
characters. This method must not be used if you have a password or some sensitive information to
be sent to the server. It is used for submitting the form where the user can bookmark the result. It
is better for data that is not secure. It cannot be used for sending binary data like images or word
documents. It also provides $_GET associative array to access all the sent information using the
GET method.
63 | P a g e
It has the following syntax in php
<?php
$_GET['variable_name'];
?>
Form validation is a necessary process before the data entered in the form is submitted to the
database. This is done to avoid unnecessary errors. In PHP Form validation, the script checks for
data in respective fields based on the rules set by the developer, and returns an error if it does not
meet the requirements.
1. Empty string
The code below checks that the field is not empty. If the user leaves the required field empty, it
will show an error message. Put these lines of code to validate the required field.
if (empty ($_POST["name"])) {
$errMsg = "Error! You didn't enter the Name.";
echo $errMsg;
} else {
$name = $_POST["name"];
}
2. Validate string
The code below checks that the field will contain only alphabets and whitespace, for example:
name. If the name field does not receive valid input from the user, then it will show an error
message.
64 | P a g e
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
3. Validate numbers
The below code validates that the field will only contain a numeric value. For example: Mobile
number. If the Mobile number field does not receive numeric data from the user, the code will
display an error message.
The input length validation restricts the user to provide the value between the specified range, for
Example - Mobile Number. A valid mobile number must have 10 digits.
The given code will help you to apply the length validation on user input.
65 | P a g e
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " .$mobileno;
}
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0001;}
</style>
</head>
<body>
<?php
// define variables to empty values
$nameErr = $mobilenoErr = $genderErr = $agreeErr= "";
$name = $mobileno = $gender = $agree="";
//String Validation
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input_data($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only alphabets and white space are allowed";
}
}
//Number Validation
if (empty($_POST["mobileno"])) {
$mobilenoErr = "Mobile no is required";
} else {
$mobileno = input_data($_POST["mobileno"]);
// check if mobile no is well-formed
66 | P a g e
if (!preg_match ("/^[0-9]*$/", $mobileno) ) {
$mobilenoErr = "Only numeric value is allowed.";
}
//check mobile no length should not be less and greator than 10
if (strlen ($mobileno) != 10) {
$mobilenoErr = "Mobile no must contain 10 digits.";
}
}
//Checkbox Validation
if (!isset($_POST['agree'])){
$agreeErr = "Accept terms of services before submit.";
} else {
$agree = input_data($_POST["agree"]);
}
}
function input_data($data) {
$data = trim($data);
$data = stripslashes($data);
return $data;
}
?>
<h2>Registration Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
Name:
<input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?> </span>
<br><br>
Mobile No:
<input type="text" name="mobileno">
<span class="error">* <?php echo $mobilenoErr; ?> </span>
<br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<span class="error">* <?php echo $genderErr; ?> </span>
67 | P a g e
<br><br>
Agree to Terms of Service:
<input type="checkbox" name="agree">
<span class="error">* <?php echo $agreeErr; ?> </span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
</form>
<?php
if(isset($_POST['submit'])) {
if($nameErr == "" && $mobilenoErr == "" && $genderErr == ""&& $agreeErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " .$name;
echo "<br>";
echo "Mobile No: " .$mobileno;
echo "<br>";
echo "Gender: " .$gender;
echo "<br>";
echo "Agree: " .$agree;
} else {
echo "<h3> <b>You didn't filled up the form correctly. </b> </h3>";
}
}
?>
</body>
</html>
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.
The htmlspecialchars() function converts special characters to HTML entities. This means that it
will replace HTML characters like < and > with < and >.
68 | P a g e
A PHP framework is a platform to create PHP web applications. PHP frameworks provide code
libraries for commonly used functions, cutting down on the amount of original code you need to
write. These frameworks save lots of time, stop rewriting the repeated code and provide rapid
application development (RAD). PHP frameworks help the developers to rapid development of
application by providing the structure.
There are many PHP frameworks but here we will discuss on the framework listed below:
1.CakePHP
CakePHP is an open-source web, rapid development framework that makes building web
applications simpler, faster and require less code.
Model is a class that deals with a database. For example, if we have users in an application
then we will have users model that deals with a database to query the table of users if we
have users model, then we will also have users table. We conclude from the example that
the model is going to have a table for that specific model.
View is a class that deals with an HTML. Everything that we can see on the application in
the browser is the view or the representation.
Controller is the middle-man that deals with both model and view. A controller is the class
that retrieves the data from the model and sends the data to the view class.
69 | P a g e
Advantages of using CakePHP in building web applications
2.Laravel
Laravel is a free and open-source PHP web framework, created by Taylor Otwell and intended for
the development of web applications following the model view controller (MVC) architectural
pattern and based on Symfony.
Laravel uses Artisan as a CLI that helps web developers to: migrate data, manage databases and
generate controllers, models and more
3. Symfony
70 | P a g e
Symfony is a free and open-source PHP web application framework and a set of reusable PHP
component libraries. It is for highly professional developer to build websites with PHP components
such as Drupal, PHPBB, laravel, and etc.
4.Zend
Zend framework is now Laminas project. It is modern framework for performing high end web
applications. This works based on Cryptographic and secure coding tools. It’s also the most used
PHP framework by enterprises.
5.Phalcon
Phalcon consist of object oriented classes to implement MVC architecture. MVC is a framework
which is used to develop web frameworks and desktop applications. Unlike other frameworks,
Phalcon optimizes performance due to its efficient memory utilization.
1. Laravel works on the object-oriented model while CakePHP works on the document-
3. Laravel is not suitable for smaller projects while CakePHP is much more suitable to build
small-scale projects.
4. From the security level view, CakePHP plays a more crucial role than that of Laravel.
71 | P a g e
6. Laravel framework is a much better choice than CakePHP in case of rapid web
7. Laravel framework is a much better choice than CakePHP in case of data backup and
handling perspective.
8. In the case of Laravel, there is a compiler functionality exists while there is no such feature
i)Popularity
Laravel is the most popular PHP framework, but Symfony still ends up high on the list at number
two.
Symfony contains reusable components, which provide more modularity. It organizes the code in
a cleaner way, making it a great fit for larger and more complex projects. This is why many
experienced PHP developers prefer Symfony over Laravel.
iii)Templating engine
Symfony provides Twig as the default templating engine. Laravel’s default templating engine
Blade has lots for everyone, Blade provides advantages over Twig, as it allows for code reusability
that doesn’t exist in Twig.
iv)Database support
Both Laravel and Symfony provide object-relational mapping (ORM) for data access. With
Symfony, Doctrine handles ORM, while Eloquent provides ORM for Laravel. With ORM, data
manipulation becomes much simpler in either PHP framework.
72 | P a g e
v)Database migrations
With Symfony, database migrations are automatic. They just need simple definitions for the fields
in the model.When considering Laravel, database migrations are manual, but they don’t require
defining the fields.
Before starting you should make sure your php version is up to date: php –v through CLI. You
should have 5.5.9 or higher. The cakephp is installed through Composer or you can download it
from github through https://github.com/cakephp/cakephp/releases.After downloading it from
GitHub, extract all the files in a folder called CakePHP in XAMPP.
After extracting it, let’s check whether it has been installed correctly or not by visiting the
following URL in browser − http://localhost/CakePHP/.
/*if (!Configure::read('debug')) :
throw new NotFoundException(
'Please replace src/Template/Pages/home.ctp with your own version or re-enable debug
mode.'
);
endif;*/
73 | P a g e
CakePHP uses Composer is a dependency management tool, as the officially supported method
for installation. To install composer on windows, download the executable file and run it.
i)Class component
Base class for an individual component. Components provide reusable bits of controller logic that
can be composed into a controller. Components also provide request life-cycle callbacks for
injecting logic at specific points.
Components can provide several callbacks that are fired at various stages of the request cycle.
The available callbacks are:initialize(),startup(),beforeRender(),shutdown() and
beforeRedirect().
ii)Controller
Application controller class for organization of business logic. Provides basic functionality, such
as rendering views inside layouts, automatic model availability, redirection, callbacks, and more.
iii)Component Collection
Component collection is used as a registry for loaded components and handles loading and
constructing component class objects.
iv)EventManager
The event manager is responsible for keeping track of event listeners, passing the correct data to
them, and firing them in the correct order, when associated events are activated. You can create
multiple instances of the object to manage local events or keep a single instance and pass it around
to manage all events in your app.
v)EventListener
An event listener is a procedure or function in a computer program that waits for an event to occur.
The listener is programmed to react to an input or signal by calling the event's handler.
74 | P a g e
Note: Dispatcher converts requests into controller actions.
The CakePHP MVC architecture has three components: Model, View and Controller, and each
has its different role.
Model
The Model layer is one that represents the logical part of your application. It retrieves the data and
convert it into meaningful concepts.
View
The View layer shows the output to the end user. It processes the inputs provided by the Model
layer and generates specific output for the end user.
Controller
The Controller layer is responsible for handling all requests coming from the users. It collects the
inputs from users and coordinate for the Model and View codes.
2.Naming conventions
CakePHP have its own naming convention standards to be used during PHP application
development. Whenever you have to create application using CakePHP you will need to create
following files first.
So, while creating above files you will have to follow CakePHP naming convention standards and
it’s very important to the PHP developer to follow these standards.
A) Database table and field naming convention
Table name must be in lowercase & plural. If there are more than one word in the table
name then words should be separated by underscore.
75 | P a g e
o Example: users, consultant_services, etc.
Field name should also be in lowercase and if more than one word then separated by
underscore
o Example: id, consultant_service_name
Foreign key name should be the (singular) name of the related table followed by _id.
o Example: user_id or consultant_service_id
B) Model naming convention
Model file names are upper camel case, more than one word should be separated by
underscore.
o Example: User.php or Consultant_service.php
Model class names are singular, usually this should be the database table name but in
singular format.
o Example: User or ConsultantService
Note: Model Files are located at app/models folder
C)Table naming convention
Table class names are plural, PascalCased and end in Table. UsersTable,
ArticleCategoriesTable, and UserFavoritePagesTable are all examples of table class names
matching the users, article_categories and user_favorite_pages tables respectively.
Entity class names are singular PascalCased and have no suffix. User, ArticleCategory, and
UserFavoritePage are all examples of entity names matching the users, article_categories
and user_favorite_pages tables respectively.
76 | P a g e
Database table: “articles”
Table class: ArticlesTable, found at src/Model/Table/ArticlesTable.php
Entity class: Article, found at src/Model/Entity/Article.php
Controller class: ArticlesController, found at src/Controller/ArticlesController.php
View template, found at src/Template/Articles/index.ctp
Application
config/routes.php
$routes->connect('/users/add'.['controller'=>'Users','action'=>'add']);
$routes->connect('/users',['controller'=>'Users','action'=>'index']);
$routes->connect('/users/edit',['controller'=>'Users','action'=>'edit']);
$routes->connect('/users/delete',['controller'=>'Users','action'=>'delete']);
src/controller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Auth\DefaultPasswordHasher;
class UsersController extends AppController{
/*Function for inserting a new record */
public function add(){
if($this->request->is('post'))
{
$username=$this->request->data('username');
$hashPswdobj=new DefaultPasswordHasher;
$password=$hashPswdobj->hash($this->request->data('password'));
$users_table=TableRegistry::get('users');
77 | P a g e
$users=$users_table->newEntity();
$users->username=$username;
$users->password=$password;
if($users_table->save($users))
echo"User is added.";
}
}
/*Function for displaying records */
public function index()
{
$users=TableRegistry::get('users');
$query=$users->find();
$this->set('results',$query);
}
/*Function for editing a record */
public function edit($id){
if($this->request->is('post'))
{
$username=$this->request->data('username');
$password=$this->request->data('password');
$users_table=TableRegistry::get('users');
$users=$users_table->get($id);
$users->username=$username;
$users->password=$password;
if($users_table->save($users))
echo"User is updated";
$this->setAction('index');
}
else{
$users_table=TableRegistry::get('users')->find();
$user=$users_table->where(['id'=>$id])->first();
$this->set('username',$users->username);
$this->set('password',$users->password);
$this->set('id',$id);
}
}
/*Function for deleting a record */
public function delete($id){
$users_table=TableRegistry::get('users');
$users=$users_table->get($id);
$users_table->delete($users);
echo"User deleted successfully.";
$this->setAction('index');
78 | P a g e
}
}
?>
src/Template/Users/add.ctp
<?php
echo $this->Form->create("users",array('url'=>'/users/add'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
src/Template/Users/index.ctp
<?= $this->Html->link("Add User",["action" =>"add"]) ?>
<table>
<tr>
<td>ID</td>
<td>Username</td>
<td>Password</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
foreach($results as $row):
echo"<tr><td>".$row->id."</td>";
echo"<td>".$row->username."</td>";
echo"<td>".$row->password."</td>";
echo"<td><a href='".$this->url->build(["controller"=>"Users","action"=>"edit",$row-
>id])."'>Edit</a></td>";
echo"<td><a href='".$this->url->build(["controller"=>"Users","action"=>"delete",$row-
>id])."'>Delete</a></td></tr>";
endforeach;
?>
</table>
src/Template/Users/edit.ctp
<?php
echo $this->Form->create("Users",array('url'=>'/users/edit/'.$id));
echo $this->Form->input('username',['value'=>$username]);
79 | P a g e
echo $this->Form->input('password',['value'=>$password]);
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
80 | P a g e
To install Laravel, first of all, you have to go C:/xampp/htdocs directory, to navigate it type
following command in your command prompt: cd c:/xampp/htdocs
Step3: Create a new directory in htdocs for your new Laravel project. Type the following
command there to install Laravel.
After running this command, it should start downloading dependencies that are required to create
the Laravel project.
Step4: The above command will install Laravel in the current directory. Start the Laravel service
by executing the following command.
81 | P a g e
php artisan serve
Step5: After executing the above command, you will get the URL(http://127.0.0.1:8000/)
Step6: Copy that URL and paste it in the browser. If you see the following screen, it implies
Laravel has been installed successfully.
82 | P a g e
4.3.3 Development of web application using Laravel
1.Root directory
Directory Description
app The app directory holds the base code for your Laravel application.
bootstrap The bootstrap directory contains all the bootstrapping scripts used for
your application.
config The config directory holds all your project configuration files (.config).
public The public directory helps to start your Laravel project and maintains
other necessary files such as JavaScript, CSS, and images of your
project.
resources The resources directory holds all the Sass files, language (localization)
files, templates (if any).
routes The routes directory contains all your definition files for routing, such
as console.php, api.php, channels.php, etc.
storage The storage directory holds your session files, cache, compiled
templates as well as miscellaneous files generated by the framework.
83 | P a g e
vendor The vendor directory holds all composer dependency files.
2.Application directory
It is the application folder and includes the entire source code of the project. It contains console
(it has Kernal.php calls the commands), exceptions (This folder contains all the methods needed
to handle exceptions. It also contains the file handle.php that handles all the exceptions.), Http
(controller and middleware), models and providers (This folder includes all the service providers
required to register events for core servers and to configure a Laravel application.).
3.Namespacing
Namespaces can be defined as a class of elements in which each element has a unique name to
that associated class. It may be shared with elements in other classes.
The use keyword allows the developers to shorten the namespace.
use <namespace-name>;
The default namespace used in Laravel is App, however a user can change the namespace to match
with web application. Creating user defined namespace with artisan command is mentioned as
follows:
php artisan app:name SocialNet
4.Service providers
Service providers are the central place of all Laravel application helping. Your own application,
as well as all of Laravel's core services, are helped via service providers.
If you open the config/app.php file included with Laravel, you will see a providers’ array. These
are all of the service provider classes that will be loaded for your application. By default, a set of
Laravel core service providers are listed in this array. These providers bootstrap the core Laravel
components, such as the mailer, queue, cache, and others. Many of these providers are "deferred"
providers, meaning they will not be loaded on every request, but only when the services they
provide are actually needed.
All service providers extend the Illuminate\Support\ServiceProvider class. Most service providers
contain a register and a boot method. Within the register method, you should only bind things
into the service container. You should never attempt to register any event listeners, routes, or any
other piece of functionality within the register method.
The Artisan CLI can generate a new provider via the make:provider command:
php artisan make:provider RiakServiceProvider
5.Service containers
84 | P a g e
The Laravel service container is a powerful tool for managing class dependencies and performing
dependency injection. Dependency injection is a fancy phrase that essentially means this: class
dependencies are "injected" into the class via the constructor method.
Let's look at a simple example:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\Models\User;
85 | P a g e
lang − This folder includes configuration for localization or internalization.
views − Views are the HTML files or templates which interact with end users and play a
primary role in MVC architecture.
8.Database
The configuration for Laravel's database services is located in your
application's config/database.php configuration file. In this file, you may define all of your
database connections, as well as specify which connection should be used by default. Most of the
configuration options within this file are driven by the values of your application's environment
variables. Examples for most of Laravel's supported database systems are provided in this file.
As the name suggests, this directory includes various parameters for database functionalities. It
includes three sub-directories:
Seeds contains the classes used for unit testing database.
Migrations this folder helps in queries for migrating the database used in the web
application.
Factories, this folder is used to generate large number of data records.
86 | P a g e
• Laravel - http://laravel.com (Currently v3.2.1)
• Twitter Bootstrap - http://twitter.github.com/bootstrap/ (Currently v2.0.4)
• jQuery - http://jquery.com (Currently v1.7.2)
Inside Laravel's root folder, you'll find a public folder - this is where all publicly accessible files
should be stored. Laravel v3.2.1 has some premade folders inside the public folder for our assets,
css, img, and js folders. Place the Twitter Bootstrap and jQuery files in their corresponding folders.
At this point, your folder structure should look similar to the following:
Twitter Bootstrap will have some files inside the css, img, and js folders, and jQuery will be inside
the js folder.
Step 2: Setup Laravel's Encryption Key, Pretty URLs and Virtual Host
If you are new to Laravel, then you should know that you have the provision to create configuration
files for Laravel application. After installing Laravel, you need to perform the permission writing
for your storage directory along with the bootstrap/cache.
Next, you have to do is, generating the application key for session securing and encrypted data
keys also. In case, the root directory doesn't have the .env file, in that case, you will have to rename
the file .env.example to .env and run the command mentioned below where you've installed the
Laravel:
php artisan key: generate
You can see in the .env file the newly generated key. Moreover, it is also possible to configure
time zone as well as a locale in the config/app.php file of your project.
Laravel allows us for running application for a diverse environment like testing, production, etc.
For configuring your application's environment, you will need the .env file which is in the root
directory of the project. When you install composer for Laravel, then this file gets generated or
87 | P a g e
created automatically by the composer itself, but if you don't install then have to rename the
specific file with the name .env.example to .env only.
You can configure the database for your application using the config/database.php file of your
project. Setting the configuration constraint utilized by various databases can also be done, and
moreover, Laravel also allowed us to use the default one as well.
Websites are regularly modified. As a developer for this, you have to put your site in maintenance
mode. In this advanced framework, it becomes easier to do that by using two artisan commands.
Let's see how to use the commands: For starting your project maintenance approach, the following
command is required:
php artisan down
After changing the required stuff, when it is time to re-run your project, the following command
is required:
php artisan up
Step 3: Setup Routing
Routing is one of the essential concepts in Laravel. Routing in Laravel allows you to route all your
application requests to its appropriate controller.
All Laravel routes are defined inside the route files located in the routes directory. When we create
a project, then a route directory is created inside the project. The route/web.php directory contains
the definition of route files for your web interface. The routes in web.php are assigned with the
web middleware group that provides the features like session state and CSRF protection. The
routes defined in routes/api.php are assigned with the API middleware group, and they are
stateless.
The routes defined in the routes/web.php can be accessed by entering the defined URL to the
browser. Let's understand this through an example.
<?php
Route::get('/', function ()
{
return view ('welcome');
});
In the above case, Route is the class which defines the static method get(). The get() method
contains the parameters '/' and function() closure. The '/' defines the root directory and function()
defines the functionality of the get() method.
88 | P a g e
In the above route, the url is '/'; therefore, we entered the localhost/laravelproject/public URL in
the web browser.
As the method returns the view('welcome'), so the above output shows the welcome view of the
Laravel.
<?php
Route::get('/example', function ()
{
return "Hello Level 5 SOD";
});
In the above example, the route is defined in which URL is '/example', so we need to enter the
URL "localhost/laravelproject/public/example" in the web browser.
o Required Parameters
o Optional Parameters
Required Parameters
The required parameters are the parameters that we pass in the URL. Sometimes you want to
capture some segments of the URI then this can be done by passing the parameters to the URL.
For example, you want to capture the user id from the URL.
<?php
Route::get('/', function()
{
return "This is a home page";
}
);
Route::get('/about', function()
{
return "This is a about us page";
}
);
Route::get('/contact', function()
{
89 | P a g e
return "This is a contact us page";
}
);
<?php
Route::get('/post/{id}', function($id)
{
return "id number is : ". $id;
}
);
The route parameters are enclosed within {} brackets, and parameters must contain alphabetic
characters. It should not contain '-' character, and instead of using this character, you can use '_'
character.
Route parameters are available in the route callbacks. Syntax of route parameters is given below:
<?php
//We can also pass the multiple parameters.
Route::get('/post/{id}/{name}', function($id,$name)
{
return "id number is : ". $id ." ".$name;
}
);
Optional Parameters
Suppose you want to specify the route parameter occasionally, in order to achieve this, you can
make the route parameter optional. To make the route parameter optional, you can place '?' operator
after the parameter name. If you want to provide the optional parameter, and then make sure that
you have also provided the default value to the variable.
Example 1:
90 | P a g e
Route::get('user/{name?}', function ($name=null) {
return $name;
});
We can also navigate from one route to another route by using named routes.
Route::get('/',function()
{
return view('student');
});
Route::get('student/details',function()
{
$url=route('student.details');
return $url;
})->name('student.details');
Step 2: Move to the resources folder and then click on the views folder.
91 | P a g e
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
In the above code, the namespace is used as it allows you to use the same function names and
classes in the different parts of the same application. For example,
namespace App\Http\functions1;
namespace App\Http\functions2;
Suppose we have to run the function having the name, i.e., RunQuery(). They are available in
different directories functions1 and functions2, so we can say that namespace avoids the collision
between the same function names.
Creating a Controller
Step 1: Type the command "php artisan make:Controller PostsController" in CMD Window
to create the Controller.
With this command provided above, we get the class without the functions such as create, update,
or delete.
This command php artisan make:controller --resource PostsController allows you to create
the controller which contains some default functions. With this command, laravel will create
controller with the following functions:
Step 2: Now move to your project and see whether the PostsController file has been created or
not. The path of the file is:
92 | P a g e
C:\xampp\htdocs\laravelproject\app\Http\Controllers
Routing controllers allow you to create the controller classes with methods used to handle the
requests.
1.Open the web.php file and write the following code:
use App\Http\Controllers\PostsController;
Route::get('/post',[PostsController::class,'index']);
In the above code, '/post' is the URL that we want to access, and PostsController is the name of
the controller. The 'index' is the name of the method available in the PostsController.php file,
and index indicates that the index() method should be hit when we access the '/post' url.
2.Add the code which is shown below as highlighted in PostsController.php file:
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
Controller Middleware
We can also assign the middleware to the controller's routes within your route files.
We can assign the middleware to the controller in the web.php file. Following are the steps
required to assign the middleware:
93 | P a g e
Step 1: First, we create a controller. We already have created the controller named
as PostsController in the previous topic.
Step 2: Now, we create the middleware, which we want to assign to the PostsController. We use
the following command to create the middleware:
Step3: Open the Check.php file created in laravelproject/app/http/Middleware directory. And add
this line in function echo "Middleware in Laravel <br><br>";
Step 4: Now, we have to add the path of the middleware Check.php in kernel.php file.
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'age' => \App\Http\Middleware\CheckAge::class,
'check'=>\App\Http\Middleware\Check::class
];
In the above code, the highlighted statement adds the path of the middleware, i.e., Check.
Step 5: Add the following code in the web.php file to assign the middleware to
the PostsController.
Route::get('/post',[PostsController::class,'create'])->middleware('check');
Step 6: Enter the URL http://localhost/laravelproject/public/post to the web browser, then see the
output.
Views
Views contain the html code required by your application, and it is a method in Laravel that
separates the controller logic and domain logic from the presentation logic. Views are located in
the resources folder, and its path is resources/views.
94 | P a g e
Let's see the simple example of views.
Step 1: First, we create the view file named Contact.php in resources/views directory.
Contact.php
<html>
<body>
<h1>Name of the Contact is : <?php echo $name; ?></h1>
</body>
</html>
Step 2: Add the following code in web.php.
Route::get('/contact', function(){
return view('Contact',['name'=>'John']);
});
In the above code, view() method contains two arguments. The first argument is the name of the
file that contains the view, and the second argument is the array passed to the given file. In array,
we are passing the name variable to the Contact.php file.
Example 2:
Step 1: First, I need to create a controller. Suppose I have created the controller named
'PostsController', and then add the code given below in a PostsController.php file.
Step 2: Now, we create the about.blade.php file in which we add the html code.
<html>
<body>
<h1>About Us</h1>
</body>
</html>
95 | P a g e
Step 3: Last step is to add the route in web.php file.
Route::get('/pos',[PostsController::class,'display']);
In laravel forms, the default method is assumed to be 'post' method if not mentioned, but we are
free to specify any other method. Since forms support Post, Put, Delete, and Get methods, so these
methods can be added in a form by using the hidden method field.
If we want to use the put method in a form, then the code is given below:
Form::open(['url'=>'Post/create , 'method'=>'Put''])
We can also open forms that point to the named routes or controller actions.
Label is a normal text which appeared in the Html form. The syntax for writing a label element in
Laravel is given below:
96 | P a g e
We can also specify the additional attributes in a label element.
o Text
Text is an area where the user can input their data. The syntax for generating a text area in Laravel
is given below:
Form::text('email');
Form::text('email','akshita123@gmail.com');
o Password
Password is an html element in a form that captures the user input, and each character is
represented in the form of (*) instead of displaying the entered digits. The syntax for the password
field is given below:
Form::password('password',['class'=>'pass']);
o Checkboxes
Form::checkbox('name','value');
By default, the checkbox is unchecked. We can also check the box by providing true value to the
checkbox element.
Form::checkbox('name','value',true);
o Radio buttons
Form::radio('name','value');
By default, the radio button is not selected. We can also select the radio button by providing true
value to the radio button element.
97 | P a g e
Form::radio(''name','value',true);
o Number
We can also add the number input field in a form. Syntax for the number input field is given below:
Form::number('name','value');
The file input field is an html element used in a form for file uploading. Syntax for file input field
is given below:
Form::file('image');
o Drop-down list
The drop-down element is used to display the list of all the pre-defined options. The syntax for
creating a drop-down menu is given below:
Form::select('digits', [1,2,3,4,5,6])
Form::select('digits',[1,2,3,4,5,6],'2')
The above code sets the value of the drop-down list with a second element of the array, i.e., 3 as
indexing starts with 0.
We can generate the grouped list through the drop-down element. Let's see this through an
example:
Form::select('animal',[
'fruits' => ['Apple','Mango','Orange'],
'Vegetables' => ['Potato','Tomato','Cabbage'],
])
Generating drop-down list with a range.
Form::selectRange('number',1,30)
Generating drop-down list with a month names.
Form.selectMonth('month')
o Date
98 | P a g e
year, month, and day. The syntax for generating a date input field is given below:
Form::date('name',\Carbon\Carbon::now())
o Buttons
We can also create the button in a web form by using the button field in a form. Let's see its syntax:
Form::submit('Click me!!')
The above line creates the submit button with the name "Click me!!".
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request; use
App\Http\Requests;
use App\Http\Controllers\Controller;
class MyController extends Controller {
99 | P a g e
public function index() { echo 'index';
}
public function create() { echo
'create';
}
public function store(Request $request) { echo 'store';
}
public function show($id) { echo
'show';
}
public function edit($id) { echo 'edit';
}
public function update(Request $request, $id) { echo 'update';
}
public function destroy($id) { echo
'destroy';
}}
Step 3 − Add the following line of code in app/Http/routes.php file.
app/Http/routes.php
Route::resource('my','MyController');
Step 4 − We are now registering all the methods of MyController by registering a controller with
resource. Below is the table of actions handled by resource controller.
Verb Path Action Route
Name
GET /my index my.index
GET /my/create create my.create
POST /my store my.store
GET /my{my} show my.show
GET /my{my}/edit edit my.edit
PUT/PATCH /my{my} update my.update
DELETE /my{my} destroy my.destroy
100 | P a g e
Step 5 − Try executing the URLs shown in the following table.
URL Description Output Image
http://localhost:8000/my Executes index method of index
http://localhost:8000/my/create MyController.php index create
Executes create method of
http://localhost:8000/my/l MyController.php create show
Executes show method of
http://localhost:8000/my/l/edit MyController.php show edit
Executes edit method of
101 | P a g e
php artisan make:migration my_blog_post Create a new migration file. Output: Created
Migration:
2019_01_27_094045_my_blog_post The new
migration file
2019_01_27_094045_my_blog_post.php will
be created under ../database/migrations./
php artisan make:model MyBlogPost Create a new Eloquent model class. Output:
Model created successfully. The new Model
file “MyBlogPost.php” will be created in
app/Models or ../app/..
php artisan route:list List all registered routes
php artisan route:clear Remove the route cache file
php artisan route:cache Create a route cache file for faster route
registration
php artisan vendor:publish Publish any publishable assets from vendor
packages
php artisan view:clea Clear all compiled view files
Step 4. Create your first Laravel View with the Blade Templating Engine
In MVC framework, the letter “V” stands for Views. It separates the application logic and the
presentation logic. Views are stored in resources/views directory. Generally, the view contains
the HTML which will be served by the application.
Example
Observe the following example to understand more about Views –
Step 1 − Copy the following code and save it at resources/views/test.php
<html>
<body>
<h1>Hello, World</h1>
</body> </html>
Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view.
app/Http/routes.php
Route::get('/test', function() { return
view('test'); });
Step 3 − Visit the following URL to see the output of the view. http://localhost:8000/test
Step 4 − The output will appear as shown in the following image.
102 | P a g e
Passing Data to Views
While building application it may be required to pass data to the views. Pass an array to view
helper function. After passing an array, we can use the key to get the value of that key in the HTML
file. Example
Observe the following example to understand more about passing data to views –
Step 1 − Copy the following code and save it at resources/views/test.php
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view.
app/Http/routes.php
Route::get('/test', function() {
return view('test',[‘name’=>’John MUHIRE’]); });
Step 3 − The value of the key name will be passed to test.php file and $name will be replaced by
that value.
Step 4 − Visit the following URL to see the output of the view. http://localhost:8000/test
Step 5 − The output will appear as shown in the following image.
103 | P a g e
});
Route::get('/test2', function() { return
view('test2'); });
Step 2 − Create two view files — test.php and test2.php with the same code. These are the two
files which will share data. Copy the following code in both the files. resources/views/test.php &
resources/views/test2.php
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
Step 3 − Change the code of boot method in the file app/Providers/AppServiceProvider.php as
shown below. (Here, we have used share method and the data that we have passed will be shared
with all the views.) app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
view()->share('name', 'Virat Gandhi');
}
/**
* Register any application services.
104 | P a g e
*
* @return void
*/
public function register() {
//
}}
Step 4 − Visit the following URLs. http://localhost:8000/test http://localhost:8000/test2
Step 5 − The output will appear as shown in the following image.
Root directory
The Root Directory Structure of Laravel
The public directory helps in starting your Laravel project and also holds other scripts (JavaScript
and CSS) as well along with images required for your project. resources. This directory is one of
the most important directories inside which you will find some other subdirectories. These are:
routes storage
Directory Description
app The app directory holds the base code for your
Laravel application.
bootstrap The bootstrap directory holds all the
bootstrapping scripts used for your application.
config The config directory holds all your project
configuration files (.config).
database The database directory holds your database
files.
routes The routes directory hold all your definition
files for routing such as console.php, api.php,
routes channels.php etc.
storage The storage directory holds your session files,
cache, compiled templates as well as
miscellaneous files generated by the
framework.
test The test directory holds all your test cases.
vendor The vendor directory holds all composer
dependency files.
Application directory
105 | P a g e
This is another Laravel directory which holds other subdirectories for additional purposes. These
are:
Directory Description
Console The Console directory contains all your project
artisan commands.
Events The Events directory hold event files that your
laravel application may pop up. Events is
Events used for sending messages or signals to
other parts of the laravel project that any action
had taken place within the project
Exceptions The Exceptions directory holds your laravel
project's exception handling files which
Exceptions handles all the exceptions thrown
by your Laravel project.
Http The Http directory holds different filters,
requests, and controllers. The Jobs directory
holds all lineup jobs in this directory. But it
does not get created Jobs initially, rather, you
need to type and run this artisan command:
make:job
Listeners The Listeners directory holds all your project's
handler class for which are used for Listeners
receiving and handling events.
Mail The Main directory holds all the emails send
by through your Laravel project, and this Mail
directory needs to be created using the
command: make:mail
Notifications The Notifications directory contains all your
transactional notifications sent through your
Notifications Laravel project, and this
directory needs to be created using the
command: make:notification
Policies The policies directory holds different policies
for your laravel project.
Providers The Providers directory is used for containing
different service providers.
Rules The Rules directory hold all the different
objects related to custom validation rules, and
Rules this directory needs to be created using
the command: make:rule
Namespacing
106 | P a g e
Namespaces can be defined as a class of elements in which each element has a unique name to that
associated class. It may be shared with elements in other classes.
Declaration of namespace
The use keyword allows the developers to shorten the namespace.
use <namespace-name>;
The default namespace used in Laravel is App, however a user can change the namespace to match
with web application. Creating user defined namespace with artisan command is mentioned as
follows –
php artisan app:name SocialNet
The namespace once created can include various functionalities which can be used in controllers
and various classes.
Service providers
Service providers are the central element of the initialization process where all the relevant and
required code is loaded by PHP. This includes all the essentials from the framework itself, but also
any own and custom code you need to load.
Bootstrap Service Providers
During the initializing process, the code bootstraps itself. That means it gets ready to go by
registering service container bindings, event listeners, middleware, configuration, and routes.
Service providers are therefore a central place to set up your application.
In the config/app.php you will find an array of providers listing all the service provider classes
that are loaded during bootstrapping. Beware that many of the service provider classes may be so-
called deferred providers. It means they are only loaded upon request, and not always included by
default. Making a provider deferred works well for classes that only need to be loaded sometimes
because it reduces the performance overhead and loads time of your web application.
Custom Service Providers
The code below is an example of a custom service provider. It extends the
Illuminate\Support\ServiceProvider class which is an abstract that requires you to define at least
a method called register. The purpose of the register method is to bind values in the service
container.
Writing Service Providers
All service providers extend the Illuminate/Support/ServiceProvider class. Most service
providers contain a register and a boot method. Within the register method. You should only blind
things into the service container. You should never attempt to register any event listeners, routes,
or any other piece of functionality within the register method. The Artisan CLI can generate a new
107 | P a g e
provider through the make::provider command. php artisan make:provider
RiakServiceProvider
Copy
The Register Method Within the register method, you should only blind thing into the service
container. You should never attempt to register any event listeners, routes, or any other piece of
functionality within the register method. Otherwise, you may accidentally use a service that is
provided by a service provider which has not loaded yet. Let's look at this code sample
<?php
namespace App\Providers; use
Riak\Connection;
use Illuminate\Support\ServiceProvider;
class RiakServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(Connection::class, function ($app)
{
return new Connection(config('riak')); });
}}
Copy
This service provider only defines a register method, and uses that method to define an
implementation of Riak//Connection in the service container.
So, what if we need to register a view composer within our service provider? This should be done
within the boot method. This method called after all other service providers have been registered.
Let's look at a simple example.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
public function boot()
{
view()->composer('view', function () {
//
});
}
}
108 | P a g e
Service containers
The Service Container in Laravel is a Dependency Injection Container and a Registry for the
application. The advantages of using a Service Container over creating manually your objects are:
Capacity to manage class dependencies on object creation: You define how an object should be
created in one point of the application (the binding) and every time you need to create a new
instance, you just ask it to the service container, and it will create it for you, along with the required
dependencies For example, instead of creating objects manually with the new keyword:
//no need to create YourClass dependencies, the SC will do that for us! $instance = App::make(
YourClass::class );
Copy
With Laravel automatic dependency injection, when an interface is required in some part of the
app (i.e. in a controller's constructor), a concrete class is instantiated automatically by the Service
Container. Changing the concrete class on the binding, will change the concrete objects
instantiated through all your app:
Copy
109 | P a g e
Copy
You can create and store unique object instances on the container and get them back later: using
the App::instance method to make the binding, and thus using the container as a Registry.
// Create an instance.
$kevin = new User('Kevin');
Copy
As a final note, essentially the Service Container -is- the Application object: it extends the
Container class, getting all the container's functionalities.
110 | P a g e