CMP517 PHP Programming R
CMP517 PHP Programming R
Chavan
Maharashtra PHP Programming
Open University
PHP Programming
Prof. Parag N. Achaliya Prof. Vivek D. Patil Ms. Monali R. Borade Dr. Pramod Khandare
Assistant Professor, Assistant Professor, Academic Co-ordinator Director
SNJB‘s Late Sau Sandip Institute of School of Computer School of Computer
K.B. Jain College of Technology and Science, Y.C.M. Open Science, Y.C.M. Open
Engineering Research centre, University, Nashik University, Nashik
Chandwad, Nashik Nashik
Production
Course Objective
Learning Outcomes:
Reference Books:
1. Php: The Complete Reference by steven holzner, Publisher: Mcgraw Hill, Latest edition
2. Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 (Learning PHP,
MYSQL, Javascript, CSS & HTML5) by Robin Nixon, O'Reilly Media, 5th edition (2018).
3. The Joy of PHP Programming: A Beginner‘s Guide to Programming Interactive Web
Applications with PHP and MySQL, Author –Alan Forbes, Latest Edition – Fifth Edition,
Publisher – Plum Island Publishing LLC.
4. Code Smart: The Laravel Framework Version 5 for Beginners by Dayle Rees.
5. Building Web Apps with WordPress: WordPress As An Application Framework by Brian
Messenlehner and Jason Coleman Foreword by Brad Williams.
6. PHP Cookbook: Solutions & Examples For PHP Programmers by Adam Trachtenberg and
David Sklar
Note: This Study material is still under development/editing process and is being made available for the sole
purpose of reference. Final edited copies will be made available once ready.
Learning Objectives:
After successful completion of this unit, you will be able to
1. Understand origin of PHP
2. Understand basics of PHP.
3. Summarize variables, constants and data types.
4. Summarize conditional statement in PHP.
5. Summarize built in functions in PHP.
This chapter will introduce you to PHP. You will learn how it came about, what it looks like,
and why it is the best server-side technology. You will also be exposed to the most important
features of the language.
This chapter will let you poke around the different variables & constants, data types,
operators, decision making & loops, predefined functions in PHP.
1.1 Introduction
The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side
scripting language designed specifically for web development. PHP can be easily embedded
in HTML files and HTML codes can also be written in a PHP file. The thing that
differentiates PHP with client-side language like HTML is, PHP codes are executed on the
server whereas HTML codes are directly rendered on the browser. In our entire course we
will be studying PHP 7 version and on an Ubuntu OS.
Step 1: Prerequisites
You must have sudo privileges account access to the Linux system. Login to your
system and upgrade the current packages to the latest available version.
sudo apt update
sudo apt upgrade
Also, install the below packages on your system.
sudo apt install ca-certificates apt-transport-https
PHP is an open source web scripting language that is widely used to build dynamic
webpages.
Leaving out the semicolon is a common error, resulting in an error message that looks
something like this:
The mechanism of separating a normal HTML from PHP code is called the mechanism of
Escaping To PHP. There are various ways in which this can be done. Few methods are
already set by default but in order to use few others like Short-open or ASP-style tags we
need to change the configuration of php.ini file. These tags are also used for embedding PHP
within HTML. There are 4 such tags available for this purpose:-
1. Canonical PHP Tags:The script starts with <?phpand ends with ?>. These tags are
also called ‗Canonical PHP tags‘. Every PHP command ends with a semi-colon (;).
Let‘s look at the hello world program in PHP:
<?php
# Here echo command is used to print
echo "Hello, world!";
?>
Output:
Hello, world!
2. SGML or Short HTML Tags: These are the shortest option to initialize a PHP code.
The script starts with <? and ends with ?>. This will only work by setting the
short_open_tag setting in php.ini file to ‗on‘.
Example:
<?
# Here echo command will only work if
# setting is done as said before
echo "Hello, world!";
?>
3. HTML Script Tags: These are implemented using script tags. This syntax is
removed in PHP 7.0.0 so its no more used.
Example:
<script language="php">
echo "hello world!";
</script>
4. ASP Style Tags: To use this we need to set the configuration of php.ini file. These are
used by Active Server Pages to describe code blocks. These starts with <% and ends
with %>.
Example:
<%
# Can only be written if setting is turned on
# to allow %
echo "hello world";
%>
phptestcli.php
Or you can type the entire path name to PHP, as in the following example:
/usr/local/php/cli/phptestcli.php
The CLI version of PHP differs from the CGI version in the following ways:
1. Outputting HTTP headers: Because the CGI version sends its output to the Web
server and then to the browser, it outputs the HTTP headers (statements the Web
server and browser use to communicate with each other). Thus, the following is the
output when the CGI version runs the script in the previous example:
Content-type: text/html
X-Powered-By: PHP/7.0
This line brought to you by PHP
You don‘t see the two headers on your Web page, but PHP for the Web sends these
headers because the Web server needs them. The CLI version, on the other hand, does
not automatically send the HTTP headers because it is not sending its output to a Web
server. The CLI output is limited to the following:
This line brought to you by PHP
2. Formatting error messages: The CGI version formats error messages with HTML
tags, because the errors are expected to be received by a browser. The CLI version
does not use HTML formatting for error messages; it outputs error messages in plain
text.
3. Providing argc and argv by default: The argc and argv variables allow you to
supply data to the script from the command line (similar to argc and argv in C and
other languages). You aren‘t likely to want to pass data to the CGI version, but you
are likely to want to pass data to the CLI version. Therefore, argv and argc are
available by default in the CLI version and not in the CGI version.
When you run PHP CLI from the command line, you can use several options that affect
the way PHP behaves. For instance, -v is an option that displays the version of PHP being
accessed. To use this option, you would type the following:
php –v
You can also display the value by using an echo statement. If you used thefollowing PHP
statements
$age = 21;
echo $age;
in a PHP section, the output would be 21.
Using an echo statement of the preceding form, with one variable only, providesthe same
basic output as the print_r statement. However, you can doa lot more with the echo statement.
You can output several items and include numbers and strings together.
For example, suppose the variable $name hasthe value Ramesh. You can include the
following line in an HTML file:
Welcome Ramesh
If you use a variable that does not exist, you get a warning message. Forexample, suppose
you intend to display $age, but type the following statementby mistake:
echo $aeg;
You get a notice that looks like the following:
Notice: Undefined variable: aeg in c:\testvar.php on line 5
The notice points out that you‘re using a variable that has not yet been givena value.
Constants are similar to variables. Constants are given names, and values arestored in them.
However, constants are constant; they can‘t be changed bythe script. After you set the value
for a constant, it stays the same. If you usea constant for weather and set it to sunny, it can‘t
be changed.
And as break
Case class const
Continue declare default
Die do echo
Else empty eval
Exit for foreach
Function global if
Include list new
Or print require
Return switch use
var while
If you‘re baffled by some code that looks perfectly okay but refuses to workcorrectly, even
after numerous changes, try changing the name of a constant.It‘s possible that you are using
an obscure keyword for your constant, andthat‘s causing your problem. This doesn‘t happen
often, but it‘s possible.Although you can use keywords for variable names, because the
beginning $tells PHP the keyword is a variable name, you probably shouldn‘t. It causestoo
much confusion for the humans involved.
1.9.1 Integer: Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point. They can be
decimal (base 10), octal (base 8) or hexadecimal (base 16). The default base is
decimal (base 10). The octal integers can be declared with leading 0 and the
hexadecimal can be declared with leading 0x. The range of integers must lie
between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1= 50;
$deci2= 654;
// octal base integers
$octal1= 07;
// hexadecimal base integers
$octal= 0x45;
$sum= $deci1+ $deci2;
echo$sum;
?>
Output:
704
1.9.2 Double: Can hold numbers containing fractional or decimal part including
positive and negative numbers. By default, the variables add a minimum number
of decimal places. Example:
<?php
$val1= 50.85;
$val2= 654.26;
$sum= $val1+ $val2;
echo$sum;
?>
Output:
705.11
1.9.3 String: Hold letters or any alphabets, even numbers are included. These are
written within double quotes during declaration. The strings can also be written
within single quotes but it will be treated differently while printing variables.
Example:
<?php
$name= "Krishna";
echo"The name of the Geek is $name \n";
echo'The name of the geek is $name';
?>
Output:
The name of the Geek is Krishna
The name of the geek is $name
1.9.4 NULL: These are special types of variables that can hold only one value i.e.,
NULL. We follow the convention of writing it in capital form, but its case
sensitive.
Example:
<?php
$nm= NULL;
echo$nm; // This will give no output
?>
1.9.5 Boolean: Hold only two values, either TRUE or FALSE. Successful events will
return true and unsuccessful events return false. NULL type values are also treated
as false in Boolean. Apart from NULL, 0 is also considering as false in boolean. If
a string is empty then it is also considered as false in boolean data type.
Example:
<?php
if(TRUE)
echo"This condition is TRUE";
if(FALSE)
echo"This condition is not TRUE";
?>
Output:
This condition is TRUE
1.9.6 Arrays: Array is a compound data-type which can store multiple values of same
data type. Below is an example of array of integers.
<?php
$intArray= array( 10, 20 , 30);
echo"First Element: $intArray[0]\n";
echo"Second Element: $intArray[1]\n";
echo"Third Element: $intArray[2]\n";
?>
Output:
First Element: 10
Second Element: 20
Third Element: 30
1.9.7 Objects: Objects are defined as instances of user defined classes that can hold
both values and functions. This is an advanced topic and will be discussed in
details in further articles.
1.9.8 Resources: Resources in PHP are not an exact data type. These are basically used
to store references to some function call or to external PHP resources. For
example, consider a database call. This is an external resource.
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
1.10.1 PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
x += y x=x+y Addition
x -= y x=x–y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
1.10.3 PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Greater than or
>= $x >= $y Returns true if $x is greater than or equal to $y
equal to
Less than or
<= $x <= $y Returns true if $x is less than or equal to $y
equal to
PHP has two operators that are specially designed for strings.
Concatenation
.= $txt1 .= $txt2 Appends $txt2 to $txt1
assignment
Non-
!== $x !== $y Returns true if $x is not identical to $y
identity
A conditional statement executes a block of statements only when certain conditionsare true.
Here are two useful types of conditional statements:
1.11.1 if statement: Sets up a condition and tests it. If the condition is true, a block of
statements is executed.
Nesting if statements
You can have an if conditional statement inside another if conditionalstatement.
Putting one statement inside another is called nesting. For example,suppose you need
to contact all your customers who live in Idaho. Youplan to send e-mail to those who
have e-mail addresses and send letters tothose who do not have e-mail addresses. You
can identify the groups of customersby using the following nested if statements:
if ( $custState == ―ID‖ )
{
if ( $EmailAdd = ―‖ )
{
$contactMethod = ―letter‖;
}
else
{
$contactMethod = ―email‖;
}
}
else
{
$contactMethod = ―none needed‖;
}
These statements first check to see if the customer lives in Idaho. If the customerdoes
live in Idaho, the script tests for an e-mail address. If the e-mailaddress is blank, the
contact method is set to letter. If the e-mail addressis not blank, the contact method is
email. If the customer does not live inIdaho, the else section sets the contact method
to indicate that the customerwill not be contacted at all.
1.11.2 Switch statement: Sets up a list of alternative conditions. It tests for the true
condition and executes the appropriate block of statements.
For most situations, the if conditional statement works best. However, sometimes you
have a list of conditions and want to execute different statements for each condition.
For example, suppose your script computes sales tax. How do you handle the different
state sales tax rates? The switch statement was designed for such situations.
The switch statement tests the value of one variable and executes the block of
statements for the matching value of the variable. The general format is as follows:
switch ( $variablename)
{
casevalue :
block of statements;
break;
casevalue :
block of statements;
break;
...
default:
block of statements;
break;
}
The switch statement tests the value of $variablename. The script then skips to the case
section for that value and executes statements until it reaches a break statement or the
end of the switch statement. If there is no case section for the value of $variablename,
the script executes the default section. You can use as many case sections as you need.
The default section is optional. If you use a default section, it‘s customary to put the
default section at the end, but as far as PHP is concerned, it can go anywhere. The
following statements set the sales tax rate for different states:
switch ( $custState )
{
case“OR” :
$salestaxrate = 0;
break;
case“CA” :
$salestaxrate = 1.0;
break;
default:
$salestaxrate = .5;
break;
}
$salestax = $orderTotalCost * $salestaxrate;
In this case, the tax rate for Oregon is 0, the tax rate for California is 100 percent, and
the tax rate for all the other states is 50 percent. The switch statement looks at the value
of $custState and skips to the section that matches the value. For example, if $custState
is TX, the script executes the default section and sets $salestaxrate to .5. After the
switch statement, the script computes $salestax at .5 times the cost of the order. The
break statements are essential in the case section. If a case section does not include a
break statement, the script does not stop executing at the end of the case section. The
script continues executing statements past the end of the case section, on to the next
case section, and continues until it reaches a break statement or the end of the switch
statement. This is a problem for every case section except the last one because it will
execute sections following the appropriate section. The last case section in a switch
statement doesn‘t actually require a break statement. You can leave it out. However,
it‘s a good idea to include it for clarity and consistency.
1.12.1 Single Line Comment: As the name suggests these are single line or short relevant
explanations that one can add in there code. To add this, we need to begin the line with (//)
or(#).
Example:
<?php
// This is a single line comment
// These cannot be extended to more lines
echo "hello world!!!";
Output:
hello world!!!
1.12.2 Multi-line or Multiple line Comment: These are used to accommodate multiple
lines with a single tag and can be extended to many lines as required by the user. To
add this, we need to begin and end the line with (/*…*/)
<?php
/* This is a multi line comment
In PHP variables are written by adding a $ sign at the
beginning.*/
Output:
hello world!
Numeric Functions
Numeric functions are function that return numeric results.Numeric php function can be used
to format numbers, return constants, perform mathematical computations etc.The table
below shows the common PHP numeric functions
<?php true
if(is_numeric (123))
{
echo "true";
}
else
{
echo "false";
Function Description Example Output
}
?>
number_format Used to formats a numeric number_format(2509663); 2,509,663
value using digit separators
and decimal points
Questions
1 Define PHP. What these tags specify in PHP <?php and ?> 5
2 Can we run PHP from HTML file? If yes, how? 5
3 Why PHP is known as scripting language? 5
4 Write a program in PHP to calculate Square Root of a number. 5
5 List different data types and explain with example. 5
6 Explain comments in PHP 5
7 List different operators and explain with example. 5
8 Write the name of PHP functions that can be used to build a function that accepts any number of arguments 5
9 Explain in details predefined functions 5
10 Explain various date and time formats. 5
11 Write a PHP script to compute factorial of n using while or for loop 5
12 Write a PHP script to display Fibonacci of length 10 5
13 Write a short note on Scope of Variables 5
14 List different loops used in PHP in details 5
15 List different decision making used in PHP in details 5
16 What is the function of for-each construct in PHP? 5
17 Explain various Math function available in PHP. 5
18 Differentiate While and Do-While statement 5
Chapter 2. PHP FORM HANDLING
Learning Objectives:
After successful completion of this unit, you will be able to
6. Summarize strings data typein PHP
7. Summarizearrays in PHP.
8. Understand GET ,POST and REQUEST methods.
9. Learn and evaluate fields reading from HTML.
10. Paraphrase PHP validation.
This chapter will introduce you to strings and arrays in PHP. This chapter will let you poke
around the different methods like GET, POST and REQUEST and also help retrieve data
from HTML form. Learn validations involved in PHP.
2.1 Strings
In any programming or scripting language, a string is a sequence of characters written
in Single quote or Double quotes. For example, "Hello Friend!" is a string written in Double
quotes. In this chapter, we will see some commonly used string manipulation functions. The
PHP string functions are part of the PHP core. Installation is not required to use these
functions in PHP.
Syntax:
strcmp($str1,$str2)
Parameters
The strcmp() function requires two strings parameter. Both the parameters are
mandatory to pass in the function.
Example:
<?php
echo strcmp("Hello ", "HELLO"). " because the first string is greater than the second
string.";
echo "</br>";
echo strcmp("Hello world", "Hello world Hello"). " because the first string is less than
the second string.";
?>
Output:
1 because the first string is greater than the second string.
-6 because the first string is less than the second string.
Remark: Second output has returned -6 because the first string is smaller than 6 characters
by the second string, including whitespace.
hello Hello 1 String1 > String2 because the ASCII value of H is 72 and
the ASCII value of h is 104 so H > h.
Hello Hello 4 String1 > String2 because the String1 is greater than the
PHP String2 by 6 characters including the whitespace.
hello Hello 1 String1 > String2 because the ASCII value of H is 72 and
PHP the ASCII value of h is 104 so H < h.
Hello Hello -4 String1 < String2 because the String1 is smaller than the
PHP String2 by 4 characters including whitespace.
Output:
Hello PHP!
PHP is the Server Side Scripting Language
format Specifies the string. Different possible format values are: Required
● %% - Returns a percent sign
● %b : Binary number
● %g : shorter of %e and %f
● %G : shorter of %E and %f
● %o : Octal number
● %s : String
Example:
<?php
$version = 7;
$str = "YCMOU";
printf("We are learning PHP %u at %s.",$version,$str);
?>
Output:
We are learning PHP 7 at YCMOU.
Example:
<?php
echo stripos("PHP is Server Side Scripting Language, I love PHP","PHP");
?>
Output:
0
13) The substr() Function:
The substr() is a built-in PHP function. This function returns a part of a string
specified by the start and length parameter. This function is supported in PHP 4 and above
versions.
Syntax:
substr($string, $start, $length)
Return Values
The substr() function returns an extracted part of the string on successful execution.
Otherwise, it will return the FALSE or empty string on failure.
Example: 1
<?php
echo substr("Hello PHPTutorial", 3). "</br>";
echo substr("Hello PHPTutorial", 0). "</br>";
echo substr("Hello PHPTutorial", 9). "</br>";
echo substr("Hello PHPTutorial", -4). "</br>";
echo substr("Hello PHPTutorial", -10). "</br>";
echo substr("Hello PHPTutorial", -16). "</br>";
?>
Output:
lo PHPTutorial
Hello PHPTutorial
Tutorial
rial
HPTutorial
ello PHPTutorial
Example: 2
<?php
echo substr("Hello PHPTutorial", 3, 8). "</br>";
echo substr("Hello PHPTutorial", 0, 9). "</br>";
echo substr("Hello PHPTutorial", 6, -4). "</br>";
echo substr("Hello PHPTutorial", 4, -7). "</br>";
echo substr("Hello PHPTutorial", -6, -10). "</br>";
echo substr("Hello PHPTutorial", -6, -1). "</br>";
?>
Output:
lo PHPTu
Hello PHP
PHPTuto
o PHPT
toria
14) The str_word_count() Function:
The str_word_count() PHP function is used to count the number of words in a string.
Syntax:
str_word_count($str)
Example:
<?php
$str = "Hello My Dear Friends!";
$wcount = str_word_count($str);
echo "No. of words in $str are ".$wcount;
?>
Output:
No. of words in Hello My Dear Friends! are 4
2.2 Arrays
An array is a special variable in any programming or scripting language which can
store more than one value at a time. For example, if you have a list of fruits, storing the fruits
in single variable could look like this:
$fruit1 = "Banana";
$fruit2 = "Mango";
$fruit3 = "Apple";
This is possible for a small amount of list items. But what if you want to store more
than 10 fruits or if you want to access a specific list item? In that case, it is not advisable to
have the variables as shown in above example. The best possible solution for the said
problems would be using an Array. An array can store multiple values using a single name,
and you can access these values by referring to the index number.
Hyundai 23 20
Honda 14 11
Maruti 7 4
Kia 11 7
We can store the above table data in a two-dimensional array like this:
$cars = array (
array("Hyundai", 23, 20),
array("Honda", 14, 11),
array("Maruti", 7, 4),
array("Kia", 11, 7)
);
Now the above two-dimensional $cars array contains four sub arrays and it has two indices:
row and column. To access the elements of the $cars array, we must point to the two indices
(row and column) as shown in below example:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Output:
Hyundai: In stock: 23, sold: 20.
Honda: In stock: 14, sold: 11.
Maruti: In stock: 7, sold: 4.
Kia: In stock: 11, sold: 7.
Sorting Array:
The elements of an array can be sorted in alphabetical or numerical order as well as in
descending or ascending order. In this section, we will see the various built-in array sorting
functions available in the PHP.
1) The sort() Function:
This function will sort the array in ascending order.
Example:
<?php
$fruits = array("Mango", "Banana", "Apple");
sort($fruits);
$length = count($fruits);
for($i = 0; $i < $length; $i++) {
echo $fruits[$i];
echo ", ";
}
?>
Output:
Apple, Banana, Mango,
2) The rsort() Function:
This function will sort the array in descending order
Example:
<?php
$fruits = array("Mango", "Banana", "Apple");
rsort($fruits);
$length = count($fruits);
for($i = 0; $i < $length; $i++) {
echo $cars[$i];
echo ", ";
}
?>
Output:
Mango, Banana, Apple,
HTTP Methods:
● GET
● PUT
● POST
● HEAD
● PATCH
● DELETE
● OPTIONS
The two most common HTTP methods are: GET and POST.
2.3.1 GET Method:
The GET method is used to request the data from the specified resource. It is one of
the most commonly used HTTP methods in HTML forms. In case of GET method, the query
string of name/value pairs is sent in the URL like this:
/sample/test_form.php?name1=value1&name2=value2
The GET method sends the user information in encoded form appended with the page
request. This page and the encoded information are separated by the ? character as shown in
above example.
Some important points about GET method:
● The GET method produces a long string that appears in server logs.
● The GET method can send upto 1024 characters only.
● If you want to send a password or other sensitive information to the server, in that
case never use the GET method.
● Binary data, like images or word documents, can't be sent using the GET method.
● PHP provides a $_GET array to access all the sent information using the GET
method.
Example:
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}?>
Output:
History Parameters are saved in browser Parameters are not saved in browser
history history
Security GET is less secure because data POST is a little safer because the
sent is part of the URL. (Never use parameters are not stored in browser
GET when sending passwords or history or in web server logs.
other sensitive information)
Visibility Data is visible to everyone in the Data is not displayed in the URL
URL
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
An error message will be shown on output if the user will leave the required field
empty. The following example checks whether the field is empty or not.
if (empty ($_POST["name"]))
{
$errMsg = "Error! Name can not be empty.";
echo $errMsg;
}
else
{
$name = $_POST["name"];
}
2.5.2 Validate String:
The following code will check that the field will contain only alphabets and
whitespace, for example - name. An error message will be shown if the name field does not
receive valid input from the user.
$name = $_POST ["name"];
if (!preg_match ("/^[a-zA-z]*$/", $name) )
{
$ErrMsg = "Only alphabets and whitespace are allowed in the name.";
echo $ErrMsg;
}
else
{
echo $name;
}
Learning Objectives:
After successful completion of this unit, you will be able to
11. Summarize file handling in PHP
12. Understand session in PHP.
13. Learn cookies in PHP.
This chapter will introduce you to file handling in PHP. You will learn how to create, open,
read, write, upload and delete files in PHP.
This chapter will let you poke around the different sessions, cookies and filters used in PHP.
3.1 Introduction:
Any web application needs to be able to handle files. For various tasks, you will often
need to open and process a file. We can use the PHP File System to create files, read them
line by line, character by character, write them, append them, remove them, and close them.
This can be done using various PHP Functions.
3.2.1 fopen():
The PHP fopen() function opens a file or a URL and returns the resource. The file
name and mode parameters are passed to the fopen() function. File name denotes the file to
be opened, while mode denotes the file mode, such as read-only, read-write, or write-only.
Syntax:
$file = fopen("filename", "mode")
The name of the file to be opened is the first parameter of fopen(), and the second
parameter defines the mode in which the file should be opened. You can open the file in one
of the following ways:
r Open a file for read only. File pointer begins at the start of the file
w Open a file for write Removes the file's contents or produces a new one if it
only. doesn't exist. The file pointer begins at the start of the
file.
a Open a file for write The data in the file is maintained. The file pointer
only. begins at the file's end. If the file does not exist, it is
created.
x Create a new file for If the file already exists, returns FALSE and an error.
write only.
r+ Open a file for read/write. The file pointer begins at the start of the file.
w+ Open a file for read/write. Removes the file's contents or creates a new one if it
doesn't exist. The file pointer begins at the start of the
file.
a+ Open a file for read/write. The data in the file is maintained. The file pointer
begins at the file's end. If the file does not exist, it is
created.
x+ Creates a new file for If the file already exists, returns FALSE and an error.
read/write.
3.2.2 fread():
The fread() function reads data from a file that is currently open. The first parameter
of fread() is the filename to read from, and the second is the maximum number of bytes to
read. Following PHP code finishes reading the file:
Syntax:
fread(file,file_size);
3.2.3 fclose():
To close an open file, use the fclose() function. Closing all files once you've done
with them is good programming practise. You don't want an open file hogging system
resources on your server! The filename or a variable containing the filename we want to close
is required by fclose().
Syntax:
fclose(filename);
3.2.4 fgets():
A single line from a file is read using the fgets() function.
Syntax:
fgets(filename);
3.2.5 feof():
The feof() function determines whether or not the file has reached the "end-of-file"
(EOF). For looping through data of unknown length, the feof() function is useful.
Syntax:
feof(filename);
3.2.6 fgetc():
A single character from a file is read using the fgets() function. The file pointer moves
to the next character after the fgetc() function is called.
Syntax:
fgetc(filename);
3.3.1 fopen():
A file can also be created using the fopen() function. In PHP, a file is created using
the same feature that opens files, which can be a little confusing. If you call fopen() on a file
that doesn't exist, it will create it if it's being used for writing (w) or appending (a).
Syntax:
$file = fopen("samplefile.txt", "w")
3.3.2 fwrite():
To write to a file, the fwrite() function is used. The name of the file to be written to is
the first parameter of fwrite(), and the string to be written is the second.
Syntax:
fwrite(file, text);
Example:
<?php
$file = fopen("samplefile.txt", "w");
$text = "Parag Achaliya\n";
fwrite($file, $text);
$text = "Vivek Patil\n";
fwrite($file, $text);
fclose($file);
?>
Output:
Parag Achaliya
Vivek Patil
3.4 File Deletion:
The file on your computer can easily be deleted using the Delete button or Shift +
Delete. By simply doing Delete operation, the file will be deleted from the current location &
will be moved to the Recycle Bin. But by doing Shift + Delete operation, the file will be
permanently deleted from the computer. If you want to delete the file using PHP then the
unlink() function will be used. The unlink() function removes a file from the system.
Syntax:
unlink(file, context)
Parameter Details:
Parameter Description
Example:
<?php
$samplefile = fopen("file.txt","w");
echo fwrite($samplefile,"Hello Friends!");
fclose($samplefile);
unlink("test.txt");
?>
It returns TRUE upon successful file deletion else FALSE on failure. It works with a
4.0 or higher version of PHP.
file_uploads = On
Step 2: Create an HTML form that allows users to upload any file they want.
<html>
<body>
<form action="upload.php" method="post">
Upload file:
<input type="file" name="FileUpload" id="FileUpload">
<input type="submit" value="Upload" name="button">
</form>
</body>
</html>
Step 3: Create an "upload.php" file containing the following code of uploading a file.
<?php
$trgt_dir = "uploads/";
$trgt_file = $trgt_dir . basename($_FILES["FileUpload"]["name"]);
$OkUpload = 1;
$FileType = strtolower(pathinfo($trgt_file,PATHINFO_EXTENSION));
if(isset($_POST["button"]))
{
$CheckFile = getimagesize($_FILES["FileUpload"]["temp_name"]);
if($CheckFile !== false)
{
echo "Valid image - " . $check["mime"] . ".";
$OkUpload = 1;
}
else
{
echo "Invalid image file.";
$uploadOk = 0;
}
}
?>
Explanation:
● $trgt_dir = "uploads/" - specifies the folder where file is uploaded
● $trgt_file specifies the location of the to-be-uploaded file
● $OkUpload=1 for future use
● $FileType - The file extension is stored in this variable (in lowercase)
● Next, determine if the image file is a genuine image or a forgery.
Note - In the directory where the "upload.php" file is located, create a new directory called
"uploads." The files you've uploaded will be saved there.
if (file_exists($trgt_file))
{
echo "The file is already exists.";
$OkUpload = 0;
}
3.6 Cookies:
To recognise a user, a cookie is frequently used. A cookie is a tiny file placed on the
user's machine by the server. The cookie will be sent each time the same machine requests a
page via a browser. Cookie values can be created and retrieved using PHP.
Syntax:
setcookie(cookie_name, cookie_value, expire, path, domain, secure, http_only);
In above syntax, the name parameter is the only one that needs to be filled out. The
rest of the parameters are entirely up to you.
3.6.2 Create/Retrieve Cookie:
Consider the following example of creating the cookie. In this example, the ―user‖
cookie with ―Parag Achaliya‖ value is created. This cookie will expire after 20 days (86400 *
20). The ―/‖ indicates that the cookie will be available on the whole website otherwise you
can select the directory you want. Then we will use the global variable $_COOKIE to retrieve
the value of ―user‖ cookie. We will also use the isset() function to check whether the cookie
is set. Remember, the setcookie() function must be used before the <html> tag.
<?php
$name = "user";
$value = "Parag Achaliya";
setcookie($name, $value, time() + (86400 * 20), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$name]))
{
echo "Cookie '" . $name . "' is not set!";
}
else
{
echo "Cookie '" . $name . "' is set!<br>";
echo "It‘s value is: " . $_COOKIE[$name];
}
?>
</body>
</html>
<?php
$name = "user";
$value = "Vivek Patil";
setcookie($name, $value, time() + (86400 * 20), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$name]))
{
echo "Cookie '" . $name . "' is not set!";
}
else
{
echo "Cookie '" . $name . "' is set!<br>";
echo "It‘s value is: " . $_COOKIE[$name];
}
?>
</body>
</html>
<?php
// set expiry date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
3.7 Sessions:
A session is a method of storing data in variables that can be used across several
pages. The data is not saved on the user's screen, unlike a cookie. When working with a
programme, you open it, make changes, and then close it. This is similar to a Session. The
computer recognises you. It knows when you start and stop using the programme. However,
there is an issue on the internet: the web server has no idea who you are or what you do
because the HTTP address does not keep track of state. Session variables address this issue
by storing user data that can be used across several pages. Session variables are stored in the
browser before the user closes it. As a result, session variables store information about a
single user and are accessible from all pages in a single programme.
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["fav_color"] = "Brown";
$_SESSION["fav_animal"] = "Lion";
echo "Session variables are set.";
?>
</body>
</html>
<?php
session_start();
?>
<html>
<body>
<?php
// Print session variables which were set in previous example
echo $_SESSION["fav_color"] . " is favorite color.<br>";
echo $_SESSION["fav_animal"] . " is favorite animal.";
?>
</body>
</html>
<?php
session_start();
?>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["fav_color"] = "Red";
echo $_SESSION["fav_color"].
?>
</body>
</html>
<?php
session_start();
?>
<html>
<body>
<?php
session_unset(); // delete all session variables
session_destroy(); // destroy the session
?>
</body>
</html>
3.8 Filters:
External input is validated and sanitised using PHP filters. Validating the data is the
process of determining whether the data is in proper format whereas Sanitizing the data is the
process of removing any illegal character from that data. Many of the functions needed for
verifying user input are included in the PHP filter extension, which is meant to make data
validation easier and faster.
Example:
<?php
$string = "<h2>Hello Friends!</h2>";
$new_string = filter_var($string, FILTER_SANITIZE_STRING);
echo $new_string;
?>
<?php
$var = 7;
if (!filter_var($var, FILTER_VALIDATE_INT) === false)
{
echo("Valid Integer");
}
else
{
echo("Invalid Integer");
}
?>
In the above example, one problem may occur if we set the value of $var to 0. It will
show the output as ―Invalid Integer‖ which is not correct. To solve this problem, we need to
do some additional programming as shown in below code,
<?php
$var = 0;
if (filter_var($var, FILTER_VALIDATE_INT) === 0 || !filter_var($var,
FILTER_VALIDATE_INT) === false)
{
echo("Valid Integer");
}
else
{
echo("Invalid Integer");
}
?>
<?php
$ip_address = "192.168.1.1";
if (!filter_var($ip_address, FILTER_VALIDATE_IP) === false)
{
echo("IP address is valid.");
}
else
{
echo("IP address is invalid.");
}
?>
<?php
$email_id = "[email protected]";
<?php
$url = "https://paragnachaliya.in/";
4.2 Introduction
Generally Error handling process is sequential process involves catching of errors generated
by program followed by taking of correct action. If you would handle errors appropriately
then it may lead to many unexpected consequences. Error handling in PHP is very easy.
Few techniques related to Process of error handling in PHP are mentioned below :
Consider, the following sample code of opening a file named ―sample.txt‖, If the file
―sample.txt‖ is not present at current location then it will give error as explained in below
mentioned sample code
\
Sample code 4.3.a
<?php
?>
Output :
Explanation :
Solution for the above mentioned code is ,With the help of die() function we can solve this
problem as explained in below mentioned sample code
<?php
if(file_exists("sample.txt")) {
else {
?>
Output :
Using set_error_handler() :
<?php
$x=10;
$y=20;
echo($z);
?>
Output :
Explanation :
using set_error_handler() function we can generate proper error as shown in below mentioned
<?php
set_error_handler("add");
$x=10;
$y=20;
echo($z);
?>
Output :
Using trigger_error() :
using trigger_error() function, it is possible to triggered error anywhere in the program where
we wish to triggered.
<?php
$x=10;
$y=2.5;
$z=$x/$y;
if ($y>=2){
?>
Output :
Explanation :
As mentioned in the above sample code if we want that value of denominator must not be
greater than zero then we can triggered the error that Value of y must be less than 2.
Addition to above mentioned methods second parameter could be added to specify an error
level. Consider below mentioned sample codes
Use of E_USER_WARNING as a second parameter :
<?php
set_error_handler("div",E_USER_WARNING);
$x=10;
$y=2.5;
$z=$x/$y;
if($y>=2) {
?>
Output :
<?php
set_error_handler("div",E_USER_ERROR);
$x=10;
$y=2.5;
$z=$x/$y;
if($y>=2) {
?>
Output :
<?php
set_error_handler("div",E_USER_NOTICE);
$x=10;
$y=2.5;
$z=$x/$y;
if($y>=2) {
?>
Output :
<?php
$x=5;
$y=10;
if($x>10) {
$z=$x+$y;
echo $z;
else {
?>
Options :
a.15
c.10
d.None of above
<?php
$x=;
$y=20;
echo $x;
?>
Options :
c.both a&b
d.None of above
<?php
set_error_handler("add",E_USER_ERROR);
$x=10;
$y=3.5;
$z=$x+$y;
if($y>=3) {
?>
Options :
a.trigger_error()
b. set_error_handler()
c.die()
d.both a&b
There are various types of errors and warnings generated after the execution of program.
Parse errors generated dues to missing or Extra parentheses, extra or braces are
unclosed,semicolon is Missing ,quotes are unclosed etc.
Parse error or syntax error can generate if the syntax mistake happened. Consider we have
php code stored in sample.php file for this file Parse error: syntax error can be anything like
unexpected ‗{‗ in sample.php or expecting ‗;‘ in sample.php on line 55
<?php
class Subject {
public $name;
function Input($name) {
$this->name = $name;
function Show() {
return $this→name;
$PHP=new Subject
$PHP->Input('PHP');
echo $PHP->Show();
?>
Output :
Explanation:
In above mentioned code 4.4.a Semicolon is missing on line 18,it gives Parse error: syntax
error. It does not refer to a quoted "VARIABLE". It means a raw identifier was encountered.
<?php
$x = 10;
y = 20;
$z=$x+$y;
echo $z;
?>
Output:
Explanation :
In above code 4.4.b Parse error: syntax error, unexpected '=' in /opt/lampp/htdocs/hi.php
on line 3 occurs because $ sign is missing in line 3
We need to solve these errors in different approaches like more regularly look at preceding
lines or comment out the code which causing problems,etc.
Self Test (Multiple Choice Questions ):
<?php
class Subject {
public $name;
function Input($name) {
$this->name = $name;
function Show() {
return $this->name;
$PHP=new Subject;
$PHP->Input('php');
echo $PHP->Show();
?>
Options:
b. php
c.name
d.None of above
<?php
$x = 10; $y = 20;
z=$x+$y;
echo $z;
?>
Options :
c.30
d.None of above
a. True b. False
$name = $_GET['name'];
$address = $_GET['address'];
echo $name;
echo $address;
?>
Output:
Notice: Undefined index: name in /opt/lampp/htdocs/hi.php on line 4
Notice: Undefined index: address in /opt/lampp/htdocs/hi.php on line 5
Explanation :
In sample code 4.5.a values are not assigned to variable $name and $ address therefore it
gives Notice of Undefined index
This error can be solved using isset () function as shown in sample code 4.5.b
if(isset($_GET['address'])){
$address = $_GET['address'];
}
else{
$address = "<br>Address not set ";
}
echo $name;
echo $address;
?>
Output :
Name not set
Address not set
For example,
error_reporting(0) indicates that all error reporting are turn off.
error_reporting(E_ERROR | E_WARNING | E_PARSE) indicates that simple errors are
running.
With the help of exception handling we can change the flow of the execution of program in
case of exception condition occurs.
Like other object oriented programming language exception handling in PHP is very simple
PHP also provides different keywords to handle exception in PHP as mentioned below
try : It is a block of code where we can code for which exception can occur
catch : If in case any exception is thrown catch block is responsible to execute that particular
exception
throw : This block is use to throw exception
finally : This block is use after the catch block
Sample Code 4.7.a
<?php
function Sample($value) {
try {
if($value == 5) {
}
echo "</br>This statement after catch will be always executed";
}
Sample(55);
Sample(5);
?>
Output :
This statement after catch will be always executed
Exception Caught properly Number is 5
Output :
This block clean all the activity
Exception Caught properly Number is 5
This block clean all the activity
Use of Exceptions
When any exception is thrown, the code next to it will not be executed, and PHP will try to
matching "catch" block. If an exception is not caught then the fatal error will be issued with
an "Uncaught Exception" message.
<?php
function checkNumber($num){
if($num>1)
return true;
checkNumber(2);
?>
Output :
Fatal error: Uncaught Exception: number must be less than or equal to 1 in
/opt/lampp/htdocs/er.php:5 Stack trace: #0 /opt/lampp/htdocs/er.php(10):
checkNumber(2) #1 {main} thrown in /opt/lampp/htdocs/er.php on line 5
<?php
function Test($value) {
try {
if($value == 9) {
catch(Exception $e) {
echo "</br>Exception Caught properly ", $e->getMessage();
finally {
Test(9);
?>
Options :
c.Number is 9
<?php
function Test($value) {
try {
if($value == 9) {
catch(Exception $e) {
Test(99);
Test(9);
?>
Options :
d.None of above
3.______ It is a block of code where we can write code for which exception can occur
Options
a.try
b.catch
c.finally
d. None of above
a.try
b.catch
c.finally
d. None of above
a.try
b.catch
c.finally
d. None of above
4.8 Summary
With the help of this unit students can understand types of errors and exceptions and also
students understand that how to handle Errors as well as Exception occurred at the time of
execution of source code.
4.9 Exercise:
3. What are the main error types in PHP and how do they differ?
5. How does one prevent the following Warning ‗Warning: Cannot modify header
information – headers already sent‘ and why does it occur in the first place?
8. Explain Basic Error Handling die() function. What will be the output of following
code?
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
Else
{
$file=fopen("welcome.txt","r");
}
?>
10. How to create Custom Error Handler? Explain error_function() with parameters in
detail.
Unit 5
PHP MySQLi
After successful completion of this unit, Students will be able to perform database
connectivity with PHP.
5.2 Introduction
This chapter focuses on MySQLi or MySQL extension with PHP. To access MySQL
database servers MySQLi functions are used.we can use MySQLi extension with MySQL
version 4.1.13 or newer.
We can use both object-oriented and procedural interface for accessing mysql database using
MySQLi.
Output :
Connection established successfully
Explanation :
In above mentioned sample code 5.3.a is having procedural approach to establish connection
with mysql and mysqli_connect function is used to establish connection with mysql
mysqli_connect() is having five parameters mentioned below
host : Name of host
username : Username to access the database
password : Password provided to the database,
dbname : Name of Database
port : Port Number
socket : Socket
3)To work with mysqli which class is instantiated via its constructor:
Options:
a.mysql
b.msqli
c.sql
d.sqli
4)Which of the following is correct syntax when the username and password is not set?
Options:
a.$cn = new mysqli("localhost", "", "");
b.$cn = new mysqli("localhost", "NA", "NA");
c.$cn = new mysqli("localhost", "_", "_");
d.$cn = new mysqli("localhost", " ", " ");
<?php
$cn = mysqli_connect("localhost","root","","mysql"); // Establish connection
if (!$cn) { // Connection Checking
Explanation :
In Sample Code 5.4.a mysqli_query() function is having two parameters,first is connection
string stored in $cn and second is query which will executes on $cn. And the result of
mysqli_query() is stored in $res.
Here in Sample Code 5.4.a we have used mysqli_fetch_array() function inside while loop to
retrieve the data in rows from database.
Self Test (Multiple Choice Questions) :
1)Which of the following is not a method of the Mysqli extrnsion?
Options:
a.fetch_array()
b.fetch_row()
c.fetch_object()
d.fetch_data()
4.Which of the following method is used inside while loop to retrieve the data in rows from
the database?
Options:
a.mysqli_query()
b.fetch_data()
c.mysqli_fetch_array()
d.mysqli_debug()
5.5 Prepared statements in MySQLi
Mysqli provides is one of the best feature named prepare statement, with the use of prepare
statement we can execute similar SQL statements repeatedly.
Prepare statements are highly efficient as the parsing time of prepare statement is very less
since the preparation for the query is done once and we can executes statements multiple
times.
$fname = "Pushkaraj";
$lname = "Kasture";
$addd = "[email protected]";
$mnumber=000000000;
$st->execute();
$fname = "Rahul";
$lname = "Patil";
$addd = "[email protected]";
$mnumber=000000000;
$st->execute();
$fname = "Atul";
$lname = "Chaudhari";
$addd = "[email protected]";
$mnumber=000000000;
$st->execute();
$st->close();
$cn->close();
?>
Output :
Records generated successfully
Explanation :
In above code 5.5.a bind_param() function is responsible to binds the parameters with the
SQL query and at the same time it specifies argument types. Types of argument can be one
of following types
s indicates string
d indicates double
i indicates integer
b indicates BLOB
Self Test (Multiple Choice Questions) :
1)With the use of _____ statement can the user execute similar SQL statements repeatedly
Option :
a.prepare
b.view
c.stored procedure
d.template
4)Which of the following does not support the SQL queries with *?
Option :
a.bind_result()
b.get_result()
c.store_result()
d.None Of the Above
5.6 Escaping Strings :
To escapes special characters from string to use in an SQL query mysqli_real_escape_string()
function is used
Syntax of mysqli_real_escape_string() function :
mysqli_real_escape_string(connection, escapestring)
<body>
<table border="1">
<tr>
<td align="center">Form Input Student Data</td>
</tr>
<tr>
<td>
<table>
<form method="post" action="">
<tr>
<td>First Name</td>
<td><input type="text" name="fname" size="20">
</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" size="40">
</td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="addd" size="40">
</td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" name="mnumber" size="40">
</td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" name="submit" value="Sent"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<?php
Output :
Explanation :
In above Sample Code 5.6.a we have escaped the special characters from the inputs taken
from HTML file .
Escapes special characters and Data get inserted.
Consider the example of Sample Code 5.8.a where we are creating the table into the database
with name staff using php
if(mysqli_query($cn,$sql)) {
echo "Table staff created successfully";
}
else{
echo "Could not create table: ". mysqli_error($cn);
}
mysqli_close($cn); //close the connection
?>
Output:
Table staff created successfully.
Explanation :
In Sample code 5.8.a we have created table in Mysql using create table query of mysql and
executed on connection using mysqli_query() function.
Consider Staff table is available with the database and we have to insert values of id and
name into the table through php.
Consider following example of Sample Code 5.8.b
If we want to enter the data into the database from web page for that reason we have to
perform the following steps :
1. Design web page in HTML
2. Pass the values from HTML to PHP code using post method
3. Insert the values into the database through insert query
<body>
<table border="1">
<tr>
<td align="center">Form Input Student Data</td>
</tr>
<tr>
<td>
<table>
<form method="post" action="">
<tr>
<td>First Name</td>
<td><input type="text" name="fname" size="20">
</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" size="40">
</td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="addd" size="40">
</td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" name="mnumber" size="40">
</td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" name="submit" value="Sent"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<?php
Consider example mentioned in Sample Code 5.8.d where updation of record is done through
update query
if(mysqli_query($cn,$sql)) {
echo "Name updated successfully";
}
else{
echo "Could not update record: ". mysqli_error($cn);
}
mysqli_close($cn); //close the connection
?>
Output :
Name updated successfully
Explanation :
In Sam ple code 5.8.d we have updated record in staff table in Mysql using update query of
mysql and executed on connection using mysqli_query() function.
Consider example of Sample Code 5.6.d where we are deleting the values from the database
using php code.
Explanation :
In Sample code 5.8.e we have deleted record in staff table in Mysql using update delete of
mysql and executed on connection using mysqli_query() function.
<?php
mysqli_query($cn, $sql);
mysqli_close($cn);
?>
Output :
mysqli_close() function use to close previously opened database connection refer code 5.10.a
where connection established with connection string $cn is close.
5.12 Joins :
SQL JOIN :
2. Left Join : Returns all records from left table matched records from right table.
3. Right Join : Returns all records from Right table matched records from left table.
4. Full Join : Returns all records from both left table and right table matched records from
both the tables.
5.13 Summary
With the help of this unit students can perform php and mysql connectivity, understand and
working meanig of funcitons required for database connectivity
5.14 Exercise :
2. Explain How is it possible to know the number of rows returned in the result set?
6. Explain the syntactical difference between procedural and object-oriented approach while
defining Mysqli functions.
Options :
a.string
b.float
c.int
d.double
Options :
b.with get_result, and then fetch_assoc (or other fetch_* variant) on the result object
c.Both
Options :
Options :
d.number is negative
Options :
a.True
b.False
Options :
a.Inner Join
b.Left Join
c.Partial Join
d.Full Join
Unit 6
Object Oriented Programming
6.1 Learning Objectives
After successful completion of this unit, you will be able to developed object oriented
functionality in PHP.
6.2 Introduction
In this chapter, we will study the various object oriented concepts such as Class,
Object, Member Function, Constructor, Destructor, Inheritance, Function Overloading,
Access Specifier, etc. used in PHP programming.
Class and Object are two major part of object oriented programming. Class consist of
member variable,member function whereas object is an instance of class.
Class is defined using class keyword followed by the classname followed by curly braces.
Below mentioned is the syntax of class
<?php
class Student {
?>
6.4 Creating Objects in PHP
new keyword is required to create Object of a class as shown in Sample Code 6.4.a.
One class may have multiple objects as shown in Sample Code 6.4.b. If we create multiple
objects of a class then every object is having all the properties as well as methods define
inside the class with different property values.
<?php
class Student {
public $name;
function Input($name) {
$this->name = $name;
function Display() {
return $this->name;
$obj=new Student;
echo $obj->Input("Vivek");
echo $obj->Display();
?>
Output:
Vivek
Explanation :
Object $obj is created by using new keyword where Student is name of class. We are passing
the string as a parameter to Input method of class by calling Input method through object $obj
and displaying the value of string using the same object.
<?php
class Student{
public $name;
function Input($name) {
$this->name = $name;
function Display() {
return $this->name;
}
$obj=new Student;
echo $obj->Input("Vivek");
echo $obj→Display();
$obj2=new Student;
echo $obj2->Input("Patil");
echo $obj2->Display();
?>
Output :
VivekPatil
Explanation :
Object $obj and $obj2 are created of same class Student using new keyword.
We are passing the string ―Vivek ‖as a parameter to Input method of class by calling Input
method through object $obj and displaying the value of string using $obj.
Similarly,We are passing the string ―Patil ‖as a parameter to Input method of class by calling
Input method through object $obj2 and displaying the value of string using $obj2.
Creating Multiple Classes and Multiple Objects:
Below is the sample code of 6.4.c contains multiple classes and multiple objects
<?php
class Student{
public $name;
function Input($name) {
$this->name = $name;
function Display() {
return $this->name;
class Staff{
public $name;
function Input($name) {
$this->name = $name;
}
function Display() {
return $this->name;
$stud_obj=new Student;
echo $stud_obj->Input("Sagar");
echo $stud_obj->Display();
$stud_obj2=new Student;
echo $stud_obj2->Display();
$staff_obj=new Student;
echo $staff_obj->Input("Mohan");
echo $staff_obj->Display();
$staff_obj2=new Student;
echo $staff_obj2->Input("Nikam");
echo $staff_obj2->Display();
?>
Output :
SagarBhosale
MohanNikam
Options :
a. New
b. Public
c. Object
d. None of above
Options :
a. 2
b. 1
c. Multiple
d. Maximum 4
Options :
a. $variable=class_name();
b. $variable=new class_name();
c. $variable=new class class_name();
d. new.$variable=class_name();
Options :
a. Instance
b. Prototype
c. a and b
d. Function
<?php
class Student {
public $name;
function Input() {
$this->name = "php";
function Display() {
return $this->name;
$obj=new Student;
echo $obj->Input();
echo $obj->Display();
?>
Options:
a.php
b.name
c.$this→name
d.None of above
With the help of object of a class we can call member function of that particular class.
We Can also call the same member functions with different properties by creating multiple
objects of the class.
Consider example of Sample Code 6.4.b,In Sample Code 6.4.b Input and Display
methods called by object name $obj and similarly same methods are called using $obj2.
<?php
class hello{
function world() {
echo‖Hello world‖;
}
$a=new hello();
$a->world();
?>
Options :
a. Error
b. True
c. No output
d. Hello World
2. We can call member function using Object of particular class with different properties.
Options :
a. True
b. False
Options:
a. Current object
b. All objects
c. Both a and b
d. None of these
6.6 Constructor Functions
Like other object oriented programming language Constructor in PHP is also used to
initialize properties of an object and also like other object oriented programming language
Constructor Functions are automatically called at the time of constructing an object.
<?php
class Student {
public $name;
function Display() {
return $this->name;
echo $obj->Display();
?>
Output :
Vivek
Explanation :
In Sample Code 6.6.a constructor is called automatically when object $obj is created and
name get initialize in constructor.
<?php
class Student {
public $name;
function Display() {
return $this->name;
// Constructor called
echo $obj->Display();
?>
Output :
Sagar
Self Test (Multiple Choice Questions)
Options:
a. Calling of method
b. constructing an object.
c. Defining class
d. Defining method
Options:
a. Construcor()
b. __construct()
c. __ constructor()
d. Construct()
Options:
a. Magic functions
c. Object of class
d. All of above
4. Constructor have
Options:
a. parameters
b. No parameters
d. a or b
6.7 Destructor
<?php
class Student {
public $name;
}
}
?>
Output :
Vivek
Explanation :
1. Destructor is called_____
Options :
Options :
a. destrucor()
b. __destruct()
c. __ destructor()
d. destruct()
Options :
a. False
b. True
6.8 Inheritance
Like other object oriented programming languages feature of Inheritance is available in PHP,
here one class is derived from the other class. The class which inherits the properties of
another class called as child class and the class which gets inherited is called parent class.
<?php
class C_Parent{
class C_Child extends C_Parent { // Child class inherits the properties of Parent class
}
}
$C_Child->Display();
$C_Child->Show();
?>
Output :
Explanation :
In the above mentioned Sample Code 6.8.a C_Child is a child class which inherits the
properties of C_Parent which is parent class using keyword extends and due to this object of
child class can access public member of parent class.
Consider Example of Sample Code 6.8.b where class three inherits the method of class two
and class two inherits the method of class one
<?php
class one{
}
class two extends one { // Child class inherits the properties of Parent class
class three extends two { // Child class inherits the properties of Parent class
$obj->Display();
$obj->Show();
$obj->out();
?>
Output :
Inside one
Inside two
Inside three
Self Test (Multiple Choice Questions)
Like other object oriented programming languages in PHP also both child and parent
classes have same function name as well as same number of parameters. With the help of
function overriding we can change the behavior of parent class method.
<?php
class C_Parent{
}
}
class C_Child extends C_Parent { // Child class inherits the properties of Parent class
$C_Parent=new C_Parent;
$C_Parent->Display();
$C_Child->Display();
?>
Output :
Explanation :
In above mentioned code of 6.f both child and parent class is having same method with name
Display() having same number of parameter (zero parameter). And to execute the Display()
method of both the classes we need to create different objects for both child and parent
classes.
6.10 Access Specifiers
Like other object oriented programming languages PHP is also having access specifiers for
controlling the access of member functions and properties of a class.
public
private
protected
public :
If we make methods or properties of a class as public then we can access these methods or
properties anywhere inside the code.
Consider an example as mentioned in below code public access specifier is applied to name
property
<?php
class Student {
public $name;
$obj->name = 'Vivek';
?>
Explanation :
In above code public access specifier is given to name so it can accessible in complete
code,so code will not give error.
Consider an example as mentioned in below code protected and private access specifiers are
applied to year and division properties respectively.
<?php
class Student {
public $name;
protected $year;
private $division;
$obj->name = 'Vivek';
?>
Output :
Error generated in output for year and division properties as both the properties are having
protected and private classifier respectively.
<?php
class Student {
public $name;
public $year;
public $division;
echo $this->name="Vivek";
$obj->Display_name(); // OK
?>
Explanation :
In above code public access specifier is given to Display_name() method so it can accessible
in complete code,so code will not give error.
Consider an example as mentioned in below code protected and private access specifiers are
applied to Display_year() and Display_division() respectively.
<?php
class Student {
public $name;
public $year;
public $division;
echo $this->name="Vivek";
echo $this->year=2019;
echo $this->division="C";
}
$obj = new Student;
$obj->Display_name(); // OK
$obj->Display_year(); // ERROR
$obj->Display_division(); // ERROR
?>
Output :
Vivek
Fatal error: Uncaught Error: Call to protected method Student::Display_year() from context
'' in /opt/lampp/htdocs/er.php:22 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/er.php
on line 22
Explanation :
Error generated in output for Display_year() and Display_division() methods as both the
methods are having protected and private classifier respectively.
6.11 Interfaces
We can say that interface is higher level of abstraction. Syntax of interface is almost
same as of class only one difference is that instead of class keyword interface keyword is
used to define interface. Interface contains just the function prototypes no any data variables.
<?php
// Implementation of FY
// Implementation of SY
?>
Explanation :
Interface is declared with name Year and Student is class which implements the interface
Year.
In PHP abstract class is declared using abstract keyword. It contains at one abstract method.
Abstract class contains both abstract and non abstract methods.
<?php
abstract class ab_base // Abstract class
?>
<?php
function Display() {
$obj->Display();
?>
Output:
In Derived class
Explanation :
Static Keyword:
<?php
class Student {
}
Student::Display();
?>
Output:
Explanation :
Static Function Display is called by class name and double colon (::).
Final Keyword :
We can use Final keyword for both the classes and methods In PHP .
If we declare any method with the final keyword then this particular method can not be
override.
<?php
class C_Parent {
function Show() {
echo "This is not final Show function in base class </br>";
function Show() {
$obj->Display();
$obj->Show();
?>
Output :
<?php
function Show() {
function Show() {
$obj->Display();
$obj->Show();
?>
Output:
Fatal error: Class C_child may not inherit from final class (C_Parent) in
/opt/lampp/htdocs/er.php on line 23
6.14 Calling Parent Constructors
Constructor of parent is not called implicitly in the child class constructor. If we want
to access parent class constructor in child class then we need to call parent::__construct().
<?php
class C_Parent {
function __construct() {
function __construct() {
parent::__construct();
?>
Output :
6.15 Namespaces
If we want to use same name repeatedly in same program creating Namespace is the best
solution for that. We can redeclare the same methods or classes in the separate namespace
within a single program without getting any error.
<?php
namespace NamspaceName {
?>
6.16 Functions
Creating Function :
function nameoffunction(){
// code that need to execute inside the function
}
Sample Code 6.16.a
<?php
function sample()
?>
Output :
<?php
$c = $a+$b;
sum(2,3);
?>
Output :
Addition is 5
<?php
function sum($a,$b)
$c = $a+$b;
?>
Output :
Addition is 5
6.17 Summary
With the help of these unit students can developed source code using object-oriented
approach in PHP
6.18Exercise:
What is a class? How object is created in PHP?
Create ‗stud‘ class in PHP. Take the RollNo, Name & MobNo of student as an input
of 10 students and display it back.
7.1.1 Laravel
Laravel is a free, open-source PHP software platform, developed by Taylor Otwell
and designed to build web applications based on the architectural template model – view –
controller (MVC) and based on Symfony. Some of Laravel's features are a scalable
packaging framework with a dedicated dependency manager, multiple ways to access
relational databases, utilities that assist in deployment and maintenance of applications, and
its bias towards syntactic sugar. Laravel is an intuitive, elegant web application platform with
a syntax. We believe creation must be a fully rewarding, fun, artistic experience. Laravel tries
to remove the pain from creation by relieving common tasks used in most web projects, such
as authentication, routing, sessions and caching.
Laravel aims to make the development process friendly to the developer, without
losing the functionality of the application. Good developers come up with the best code. To
this end, we have tried to combine the very best of what we've seen in other software
architectures, including frameworks implemented in other languages like Ruby on Rails,
ASP.NET MVC, and Sinatra. Laravel is open but efficient, providing powerful tools that are
required for stable, wide applications. A superb container reversal, articulate migration
framework, and tightly integrated unit testing help give you the resources you need to
develop any application you are tasked with.
7.1.2 CodeIgniter
CodeIgniter is a web platform for rapid development of open-source software for use
with PHP in creating interactive websites. It is loosely based upon the development pattern of
the popular model – view – controller (MVC). While controller classes within CodeIgniter
are a necessary part of development, models and views are optional. CodeIgniter may also be
updated to use Hierarchical Model View Controller (HMVC) which allows developers to
maintain modular Controller, Model and View grouping organized in a subdirectory format.
As compared to other PHP frameworks, CodeIgniter is most often noted for its speed.
In an overall critical look at PHP frameworks, PHP developer RasmusLerdorf spoke at
frOSCon in August 2008, saying he liked CodeIgniter "since it is faster, lighter and the least
like a frame."
7.1.3 CakePHP
CakePHP is a Web application that is open source. It implements the model – view –
controller (MVC) method and is written in PHP, based on the Ruby on Rails framework, and
licensed under the MIT License. CakePHP uses well-known principles in software
engineering and trends in software design, such as configuration convention, model – view –
controller, active record, association data mapping and front control.
CakePHP began in April 2005, when Michal Tatarynowicz, a Polish programmer,
wrote a minimal version of a rapid application development framework in PHP, dubbing it
Cake. He released the code under the MIT license, and opened it up to developers ' online
community. As of December 2005, L. Masters G. J. Woodworth established the Cake
Software Foundation to promote CakePHP related development. As of May 2006, version 1.0
was released. One of the inspirations of the project was that of Ruby on Rails, using many of
their ideas. Many sub-projects have since developed and spawned in the community. In
October 2009, Woodworth project manager and developer N. Abele resigned from the project
to focus on their own projects, including the Lithium Web Project (formerly part of
CakePHP). The remaining development team decided to work on the aforementioned initial
roadmap.
7.1.4 Yii
Yii is an open source, object-oriented Web application framework for MVC PHP
component-based applications. Yii is pronounced as "Yee" or [ ji: ] and it means simple and
evolutionary" in Chinese and can be an acronym for "Yes It Is!". Yii started as an attempt to
fix perceived PRADO platform drawbacks: slow handling of complex websites, steep
learning curve, and difficulty in customizing many controls. Yii is a popular platform for
Web programming, meaning it can be used with PHP to build all sorts of Web applications.
Its component-based architecture and sophisticated caching support make it particularly
suitable for the development of large-scale applications such as portals, forums, content
management systems (CMS), e-commerce projects, RESTful Web services, and so on.
Model – It is the pattern's central component. It is the dynamic data structure of the program,
independent of user interface. It manages the application‘s data, logic, and rules directly.
View – It is any sort of information representation, such as a map, diagram, or table. Multiple
views of the same information, such as a management bar chart and a tabular view for
accountants are possible.
The model – view – controller architecture, in addition to dividing the application into those
components, determines the interactions between them.
The model is responsible for handling application data. It receives controller user
input.
The view implies the model is viewed in a particular format.
The controller reacts to user input and performs interactions on objects of the data
model. The controller receives the data, validates it internally and then transfers the
input onto the computer.
Code Reuse
It is possible to refact the same (or similar) view for one application with different
data for another application, because the view is simply handling how the data is displayed to
the user. Unfortunately this does not work when this code is also useful for user input
handling.
7.1.5.3 Advantages &Disadvantages
Advantages
Simultaneous development – Multiple developers can work on the model, controller
and views at the same time.
High cohesion – MVC allows for the logical grouping of similar actions together on a
controller. There are also groupings of views for a particular model.
Loose coupling – The very nature of the MVC framework is such that models, views
or controllers are lowly coupling.
Ease of modification – Future development or modification is simpler, because of the
separation of responsibilities.
Multiple views for a model – Models can have many different views.
Disadvantages
The drawbacks of MVC for wrongly factored applications may usually be defined as
overhead.
Code navigability – The navigation system can be challenging because it introduces
new levels of abstraction and requires users to conform to MVC's requirements for
decomposition.
Multi-artifact consistency – The decomposition of a feature into three artefacts causes
dispersion. Thus, require developers to keep multiple representations consistent at
once.
Undermined by inevitable clustering – Applications appear to communicate strongly
between what the user sees and what the user is using. Hence, the computation and
state of each function appears to be clustered into one of the 3 program parts erasing
MVC's purported advantages.
Excessive boilerplate – Because the application computation and state are typically
clustered into one of the 3 parts, the other parts degenerate into either boilerplate
shims or code-behind which only exist to satisfy the MVC pattern.
Pronounced learning curve – Multi-technology knowledge becomes norm. Developers
who use MVC need to be experienced in various technologies.
Lack of incremental benefit – UI implementations are already factored into modules,
gaining code reuse and independence through the design of components, leaving
MVC no incremental gain.
7.2 Laravel Installation
7.2.1 Server Requirements
There are a few program specifications to the Laravel framework. The Laravel
Homestead virtual machine meets all of these criteria, so it is highly recommended that you
use Homestead as your local development environment in Laravel.
If you don't use Homestead, however, you will need to ensure that your server meets
the following requirements:
PHP >= 7.1.3
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Ctype PHP Extension
JSON PHP Extension
BCMath PHP Extension
Make sure you place the system-wide vendor bin directory for the composer in your $PATH
so that your system can locate the Laravel executable. Based on your operating system, this
directory exists at various locations; however, some common locations include:
macOS: $HOME/.composer/vendor/bin
GNU / Linux Distributions: $HOME/.config/composer/vendor/bin
When mounted, the laravel new command will establish a fresh installation of Laravel in
the directory you choose. For example, laravel new web will create a web named directory
containing a fresh Laravel installation already installed with all of the Laravel dependencies:
Configuration
Public Directory
You should configure the document / web root of your web server after installing Laravel to
be the public directory. In this directory the index.php acts as the front controller for all
HTTP requests that access your domain.
Configuration Files
All Laravel application configuration files are mostly stored in the config directory. Each
option is documented so be free to browse through the files and familiarize yourself with the
options available.
Directory Permissions
You may need to configure certain permissions once you have installed Laravel. Storage
directories and bootstrap/cache directories should be writable through your web server, or
Laravel won't run. If you are using the virtual Homestead system, you should already set
these permissions.
Application Key
After installing Laravel, the next thing you should do is set your application key to a random
string. If you have installed Laravel via Composer or the Laravel installer, the php artisan
key: generate command has already set this key for you.
This string will normally have to be 32 characters long. The key can be set within the file for
the .env environment. If the .env.example file has not been renamed to .env, you should
do that now. If the application key is not set it will not be secure for your user sessions
and other encrypted data!
Additional Configuration
Almost no other configuration from the box is required by Laravel. You're free to begin
development! You may want to test the config / app.php file and its documentation
though. This includes many choices that you may want to modify according to your query,
such as timezone and locale.
RewriteCond%{HTTP: Authorization}.
RewriteRule.*-[E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond%{REQUEST_FILENAME}!-d
RewriteCond%{REQUEST_FILENAME}!-f
RewriteRule^index.php[L]
Nginx
If you use Nginx, all requests will be directed to the index.php front controller via the
following directive in your site configuration:
location /{
try_files$uri$uri//index.php?$query_string;
}
Configuration
Laravel makes it extremely simple to connect to databases, and to run queries. The database
configuration file is app/config/database.php. You can define all of your database
connections in this file, and specify which connection should be used by default. The file
provides examples for all of the available database systems.
Currently Laravel supports four database systems: MySQL, Postgres, SQLite, and SQL
Server.
Running Queries
Once you have configured the link to your database, you may use the DB class to run queries.
DB::table('posts')->delete();
});
Note: Any exception thrown into the closing of the transaction would cause the
transaction to be immediately rolled back.
You may need to start a transaction sometimes by yourself:
DB::beginTransaction();
A transaction can be rollbacked using rollback method:
DB::rollback();
Finally, the commit method allows you to commit a transaction:
DB::commit();
Accessing Connections
You can access these via DB::connection method when using multiple connections:
$users=DB::connection('foo')->select(...);
You can also access the raw PDO case, which underlies:
$pdo=DB::connection()->getPdo();
If you want to disconnect from the specified database due to more than the underlying PDO
instance's max_connections limit, use the disconnect method:
DB::disconnect('foo');
Query Logging
By default Laravel keeps a log of all queries running for the current request in memory.
However, in some cases this can cause the application to use excess memory, such as when
inserting a large number of rows. To disable the log, you may use the disableQueryLog
method:
DB::connection()->disableQueryLog();
You can use getQueryLog method to get an array of the queries you have executed:
$queries=DB::getQueryLog();
Exercise:
1. What is framework? List various PHP frameworks.
2. Explain the reason to use the PHP frameworks.
3. Explain MVC along with its goal.
4. State the various advantages and disadvantages of MVC.
5. List the system requirement for the installation of the Laravel framework.
6. State the various steps involved in the installation of the Laravel framework.
8. Introduction to CMS
In this chapter, we are going to study the concept of Content Management System
(CMS), various CMS tools used to design the website, installation of WordPress, website
8.1 Introduction
create, edit, organize, and publish.WordPress is a content management system that enables
you to build your content and publish it on the internet.While being mostly used for web
WordPress allows users to have complete control over the files, documents, and
interface design and display. To publish content using WordPress, you do not need to know a
single line of code.The beauty of a good content management system is to allow any user
Average user or small business in the earlier days had to rely on static HTML pages
because they couldn't afford a content management system that would cost hundreds of
thousands of dollars.That problem has now been solved. WordPress is free and open source
WordPress is used creatively in all manner of ways.We've seen WordPress being used
to power small business websites, forums, large university websites, portfolios, real estate
listing platform, company internal communication network, online archives, film repositories,
application technology base, arcade pages, and anything else you may think of.
There are various content management systems that will provide the features
Joomla
Drupal
Magento
8.1.1 WordPress
PHP & MySQL.The features include a design module and a prototype framework.It is mostly
related to blogging but embraces other forms of web content including more conventional
mailing lists and forums, media galleries, and online stores.Used as of April 2019 by over 60
million websites, including 33.6 percent of the top 10 million websites, WordPress is the
most popular website management system in use.WordPress was also used in other
WordPress was launched May 27, 2003 as a b2/cafelog fork by its owners, Matt
Mullenweg and Mike Little.The software is published (or later) under the GPLv2 license.To
function, WordPress has to be installed on a web server, either as part of an Internet hosting
package to act as a network host in its own right.A local machine may be used for the
8.1.2 Joomla
Joomla is a free and open source content management system (CMS) created by
Open Source Matters, Inc. for the publication of web content.It is built on a web application
framework for model – view – controller which can be used independently of the CMS.
1.5) and software design patterns, stores data in a database called MySQL, MS SQL (since
version 2.5), or PostgreSQL (since version 3.0), and includes features such as web loading,
RSS feeds, printable page versions, news alerts, forums, search and language
internationalization support.
There are more than 8,000 free and commercial extensions available from the official
Joomla Extensions Directory, and more from other sources.It is estimated to be the second
8.1.3 Drupal
Drupal is a free and open-source content management system developed under the
GNU General Public License and distributed under PHP.Drupal provides at least 2.3 per cent
of all websites worldwide with a back-end framework – ranging from personal blogs to
corporate, political, and government sites.Drupal is also used by systems for knowledge
The Drupal ecosystem comprised more than 1,37 million members as of March 2019,
including 114,000 actively contributing users, resulting in over 42,650 free modules which
extend and customize the Drupal functionality, more than 2,750 free themes that modify the
look and feel of Drupal, and at least 1,270 free distributions that allow users to set up a
Drupal's initial version, known as the Drupal core, includes basic features common to
menu management, RSS feeds, taxonomy, configuration of the page layout, and system
management.The installation of the Drupal core can be a basic website, a single- or multi-
popular frameworks, Drupal meets most of the functionality specifications generally accepted
Drupal runs on any computing platform that supports a web server that can run PHP,
8.1.4 Magento
originally developed with the assistance of volunteers by Varien, Inc, a US private company
update.Roy Rubin, Varien's former CEO, later sold a large share of the company to eBay,
which ultimately purchased it completely and then sold it to Permira; Permira subsequently
sold it to Adobe.
Magento 2.0 was released on 17th November 2015.Among the features which have
scalability, rich built-in data snippets, new file structure with easier customization,CSS
Preprocessing using a resolution of the LESS & CSS URL, improved performance and a
more organized code base.Magento uses the relational database management system MySQL
or MariaDB, the programming language for PHP, and the Zend Framework elements.It
architecture.In addition, Magento uses the model entity – attribute – value to store data.In
addition, using the JavaScript library Knockout.js, Magento 2 introduced the Model-View-
cafelog.As of May 2003, b2/cafelog was reported to have been built on around 2000 blogs.It
was written in PHP by Michel Valdrighi, who is now a contributing WordPress developer, for
use with MySQL.Though WordPress is the official successor, there is also another project,
between Matt Mullenweg and Mike Little to build a b2 fork.The word WordPress was coined
all websites whose content management system is established are using WordPress.This
WordPress is and does.It stores your content that allows you to create and publish web pages
that only require a domain and a working hosting site.WordPress uses a template processor to
have a Web design program.The architecture is a front controller, which routes all non-static
URI requests into a single PHP file that parses the URI and defines the target page.This
8.2.2 Installation
WordPress is very easy and simple to install.Through the hosting, we'll see step by
Step 1:Login to the cPanel of the website where you want to install the WordPress.
Step 2: After successful login, cPanel dashboard will get open. At the bottom of this
dashboard, there is tab as Softaculous Apps Installer. Click on the WordPress under this tab.
empty under Software Setup part. Also select the theme then click on Install button.
Step 5: WordPress will be installed successfully after the completion of above step & the
Step 6: Now you can see that the WordPress website is ready to use & edit.
8.2.3 Dashboard
The Dashboard's key idea is to give you a place to get an at-a-glance rundown of
what's happening to your site.You can catch up on news, view your draft articles, see who's
linking to you or how popular your content has been, easily message a no-frills post, or check
your latest comments out and moderate.It's like an eye view of operations from a bird, from
which you can swoop down into the specific details. The Dashboard contains the following
modules:
At a Glance
Quick Draft
Activity
Your Stuff
What‘s Hot
Stats
At a Glance
The module At a Glance is just as it sounds!It gives a "at-a-glance" look at the posts,
sites, reviews, theme and spam posts on your blog.Click on the links, and you will be taken to
the corresponding screen.Akismet's caught track of your total comments and spam.You can
also click on the numbers to load the screen with relevant comments.
Quick Draft
Quick Draft is a mini-post editor, which allows the Dashboard to create instant
content.In the post you can include a title and body text, and save it as a Draft.You should
use the Add New Post screen for additional options, such as adding categories or setting a
future publication date.Below you will see links to your most recent drafts, allowing a one-
click Dashboard access.When you click on any of them, editing the post should take you
straight away.
Activity
The module has many new features that make working with the Dashboard's
Your Stuff
On WordPress.com, the Your Stuff module shows links to your recent activity.The
module will display links to comments you have left on other WordPress.com blogs, as well
as links to posts on any of your blogs where you have made changes recently.
What's Hot
Stats
The module Stats is a favorite among many users. It will show you a graph of the
traffic in your blog and links to some popular areas of your site. The graph simply works like
the graphs on the Site Stats screens, so you can click a point to see more information about
WordPress Posts are entries that appear in reverse chronological order on the home
page of the blog or on the posts page. If any sticky posts are made, they will appear before
the other posts. You can find posts in the Archives Categories Recent Post, and other widgets.
Posts are shown in the blog's RSS feed, too. In Reading Settings, you can control how many
Step 1: You must first log in to your site's wp-admin panel, then go to Posts -> Add New.
Step 2: You'll see the WordPress posts editor on this page. The core parts of this page are:
Post Title - In this field enter the title of your post. It will show above your content on
your theme.
Post Content - You can add the actual content of your post to WordPress
WYSIWYG editor. Note that it does have two tabs - Visual (To format your text, use
Step 4: You can go to your site's front page now to check out the newly created blog post.
8.2.5 Media Library
The Media Library is where all of your images audio, videos and documents can be
Click Add New to select the files you want to upload, or drag and drop files directly
Menu must be defined before various items are added to it. Menu can be created in
2. Select the Menus option to bring up the Menu Editor from the Appearance menu on
4. In the Menu Name box type a name for your new menu
Different types of links can be added to the menu; these are divided between panes
3. Tap the checkbox next to the title of each page to pick the Pages you want to add.
4. To add your selection(s) to the menu you created in the previous step, click the Add
5. Once you have added all the menu items you want, press the Save Menu button.
1. Locate the menu item you wish to delete in the menu editor window
2. To expand it, press the arrow icon in the top right corner of the menu item / window.
3. Click the Link to Remove. The menu item / box shall be deleted immediately.
When planning menu structure it helps to consider each menu item as a heading in a
formal report document. In a formal report, the headings of the main section (Level 1
headings) are the closest to the left of the page; the headings of the sub-section (Level 2
headings) are slightly further to the right; any other subordinate headings within the same
The WordPress menu editor allows a quick 'drag and drop' interface to construct
multi-level menus. Drag up or down the menu items to change their appearance in the menu.
To create sub-levels within your menu, drag the menu items left or right.
You need to place the 'child' underneath its 'parent' and then move it slightly to the
After completing above mentioned steps, your newly created website will get ready on the
specified domain or locally. You can see the website by entering the URL in address bar of
your browser.
Exercise: