SlideShare a Scribd company logo
1 of 127
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
BCA
Semester: FIFTH Semester
Name of the Subject:
WEB BASED PROGRAMMING (PHP)
Unit-1
FACULTY NAME: Ms.Rekha Jain
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
UNIT-1
INTRODUCTION TO WEB APPLICATIONS
The term web application refers to a software system that provides a
user interface through a web browser. Examples of web applications
include blogs, online shopping, search engines, etc.
Static web pages are stored in the file system of web server usually
displays the same information to all visitors. Whereas dynamic pages
are constructed by a program that produce the HTML. This type of
web application provide individual information to the user and let
them personalize the content according to their preferences.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
ABOUT HTML
HTML stands for Hyper Text Markup Language. It is used to design web pages using markup
language. HTML is the combination of Hypertext and Markup language. Hypertext defines
the link between the web pages. Markup language is used to define the text document
within tag which defines the structure of web pages. This language is used to annotate
(make notes for the computer) text so that a machine can understand it and manipulate
text accordingly. Most of markup (e.g. HTML) languages are human readable. Language
uses tags to define what manipulation has to be done on the text.
HTML is a markup language which is used by the browser to manipulate text, images and
other content to display it in required format. HTML was created by Tim Berners-Lee in
1991. The first ever version of HTML was HTML 1.0 but the first standard version was HTML
2.0 which was published in 1999.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Client Side Scripting Vs Server Side Scripting
A script is generally a series of program or instruction, which has to be executed on other
program or application. The scripts can be written in two forms, at the server end (back
end) or at the client end (server end).
Basis for
comparison
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
Basic Works in the back end which could
not be visible at the client end.
Works at the front end and
script are visible among the
users.
Processing Requires server interaction. Does not need interaction
with the server.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Languages involved PHP, ASP.net, Ruby on
Rails, ColdFusion, Python,
etcetera.
HTML, CSS, JavaScript, etc.
Affect Could effectively
customize the web pages
and provide dynamic
websites.
Can reduce the load to the
server.
Security Relatively secure. Insecure
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Conclusion:
Client-side scripting and server-side scripting works in a coordinated manner with each
other. However, both the scripting techniques are very different, where the client-side
scripting emphasize on making the interface of the web application or website more
appealing and functional. Conversely, server-side scripting emphasizes on the data
accessing methods, error handling and fast processing etc.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
LOCAL SERVER AND REMOTE SERVER
Understanding the difference between a Local Server and a Remote server is
very important. If you are referring to a Local Server, this means that you have a
server setup on your current machine. When the server is Remote, this just
means that it is on another computer.
You may have heard the phrase, "Working Remotely." What this means is that
the person will not be working in the office, instead they could be working at
home or from their favorite corner coffee shop. So since that person is away
from the office, they are considered "Remote." In the same case if a server
hosting your files is not in-house or on your computer, it is considered to be a
Remote Server.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
LOCAL SERVER AND REMOTE SERVER
First let's talk about what happens when you visit a web page in your browser. Well, your
computer needs to contact a (remote) server on the web and then send the data back to
your computer:
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
LOCAL SERVER AND REMOTE SERVER
But when you are running a local server, your computer contacts itself since it
is running a local server and returns the data back to the browser:
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
INSTALLING WEB SERVERS
Web server is a computer where the web content is stored. Basically web
server is used to host the web sites but there exists other web servers also
such as gaming, storage, FTP, email etc.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS) and Personal Web Server(PWS)
What is IIS - Internet Information Server ?
• Internet Information Server (IIS) is one of the most popular web servers from
Microsoft that is used to host and provide Internet-based services to ASP.NET
and ASP Web applications.
• A web server is responsible for providing a response to requests that come
from users.
• When a request comes from client to server IIS takes that request from users
and process it and send response back to users.
• Internet Information Server (IIS) has it's own ASP.NET Process Engine to
handle the ASP.NET request.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS) and Personal Web Server(PWS)
Internet Information Server
• This basic functionality allows web servers to share and deliver information
across local area networks (LAN), such as corporate intranets, and wide
area networks (WAN), such as the internet.
• A web server can deliver information to users in several forms, such as
static webpages coded in HTML; through file exchanges as downloads and
uploads; and text documents, image files and more.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
IIS 5.0
– Enterprise-level Web server
– Included with Windows 2000
– Allows computer to serve documents
• Internet Services Manager (Fig. 1.1)
– Open Control Panel, double click Administrative Tools
icon, then double click Internet Services Manager icon
– Administration program for IIS
– Place documents to be requested in default directory or
virtual directory
• Default: C:InetpubWwwroot
• Virtual: alias for existing directory on local machine
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
F.g. 1.1 Internet Services Manager dialog
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
• Default FTP Site and Default Web Site
– Permit transferring documents between computer and server
– HTTP used frequently to request documents
• Default SMTP Virtual Server
– Allows for creation of mail server
• Create virtual directory in Default Web Site
– Most Web documents reside in Webpub directory
• Right click Webpub, select New, then Virtual Directory
• Initiates Virtual Directory Creation Wizard (Fig. 1.2)
– Guides user through virtual directory creation process
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
F.g. 1.2 Virtual Directory Creation Wizard welcome dialog
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
• Virtual Directory Alias (Fig. 1.3)
– Enter name for virtual directory
• Name should not conflict with an existing virtual directory
• Web Site Content Directory (Fig. 1.4)
– Enter path of directory containing Web documents
• Access Permissions (Fig. 1.5)
– Presents security level choices
– Select access level appropriate for Web document
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
F.g.1.3 Virtual Directory Alias dialog.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
F.g. 1.4 Web Site Content Directory dialog.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS)
• Access Permissions (Fig. 1.5)
– Presents security level choices
– Select access level appropriate for Web document
– Read allows users to read and download files
– Run Scripts allows scripts to run in directory
– Execute allows applications to run in directory
– Write allows Web page to accept user input
– Browse allows users to navigate between documents
– Read and Run Scripts selected by default
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
F.g. 1.5 Access Permissions dialog
Internet Information Server(IIS)
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS) and Personal Web Server(PWS)
What is Personal Web Server (PWS) ?
• Personal Web Server (PWS) is a web server application from Microsoft that allows a
user to save, selectively publish and share posts on the World Wide Web or a local
network.
• Personal Web Server differs from all other types of Web servers in the way that it is
controlled and operated by an individual rather than a company.
• PWS can be used to support Web pages if it is attached to a continuous Internet
connection.
• It can also help websites to generate more traffic in an offline mode by staging
websites before they are published globally.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Internet Information Server(IIS) and Personal Web Server(PWS)
Installing Microsoft Personal Web Server
The nice thing about Microsoft Personal Web Servers is that it is a free download from
the Microsoft web site at http://www.microsoft.com/windows/ie/pws/. It is a very
easy install. After you download the software, you will have an executable installation
file. When you click on the file to install, it will not prompt you for installation
questions. It simply installs where it wants to on your C drive. After the software is
installed, it requires a reboot of your system. After the system reboot, the PWS icon
will be running in the System tray, and it will also add an icon to your Control Panel.
From either location, you can access configuration settings to customize and configure
PWS for your needs. The HTTP process starts by default, but if you want to run the FTP
process, you will have to configure it to start up automatically.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Static website vs Dynamic website development
Static website
Static website is the basic type of website that is easy to create. You don't need the
knowledge of web programming and database design to create a static website. Its web
pages are coded in HTML.
The codes are fixed for each page so the information contained in the page does not
change and it looks like a printed page.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Static website vs Dynamic website development
Dynamic website
Dynamic website is a collection of dynamic web pages whose content changes
dynamically. It accesses content from a database or Content Management
System (CMS). Therefore, when you alter or update the content of the database,
the content of the website is also altered or updated.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Static Website Dynamic Website
Prebuilt content is same every
time the page is loaded.
Content is generated quickly and
changes regularly.
It uses the HTML code for
developing a website.
It uses the server side languages
such as PHP,SERVLET, JSP, and
ASP.NET etc. for developing a
website.
It sends exactly the same
response for every request.
It may generate different HTML for
each of the request.
The content is only changed when
someone publishes and updates
the file (sends it to the web
server).
The page contains "server-side"
code which allows the server to
generate the unique content when
the page is loaded.
Flexibility is the main advantage of
static website.
Content Management System
(CMS) is the main advantage of
dynamic website.
Static website vs Dynamic website development.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
BCA
Semester: FIFTH Semester
Name of the Subject:
WEB BASED PROGRAMMING (PHP)
Unit-2
FACULTY NAME: Ms.Rekha Jain
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
UNIT-2
INTRODUCTION TO PHP
PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back
in 1994.
• PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
• PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
• It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
• PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
INTRODUCTION TO PHP
• PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4
added support for Java and distributed object architectures (COM and CORBA), making
n-tier development a possibility for the first time.
• PHP Syntax is C-Like.
• PHP can handle forms, i.e. gather data from files, save data to a file, through email you
can send data, return data to the user.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
INTRODUCTION TO PHP
Characteristics of PHP:
Five important characteristics make PHP's practical nature possible −
• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Example of php script:
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal
HTML you'll have PHP statements like this −
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result −
Hello, World!
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Start and End tags of PHP
The PHP syntax is a set of rules that define how a program should be written.
All code written in PHP must be identified as PHP code. A set of tags are used to
mark the beginning and end of a block of code, in between which any amount of
code can be written.
• The standard opening tag is:
<?php
• The standard closing tag is:
?>
Note: PHP statements end with a semicolon (;).
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Data types in PHP
Variables can store data of different types, and different data types can do
different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes:
$x = "Hello world!";
$y = 'Hello world!';
PHP Integer
• An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
• Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base
8), or binary (base 2) notation
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
• In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
• A float (floating point number) is a number with a decimal point or a number in
exponential form.
e.g. $x = 10.365;
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing.
$x = true;
$y = false;
PHP Array
• An array stores multiple values in one single variable.
• In the following example $cars is an array.
$cars = array("Volvo","BMW","Toyota");
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Object
• An object is a data type which stores data and information on how to process that data.
• In PHP, an object must be explicitly declared.
• First we must declare a class of object. For this, we use the class keyword. A class is a
structure that can contain properties and methods:
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP NULL Value
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Variables in PHP
• Variables are "containers" for storing information.
Creating (Declaring) PHP Variables
• In PHP, a variable starts with the $ sign, followed by the name of the variable:
• <?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Variables
• A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
• Rules for PHP variables:
1. A variable starts with the $ sign, followed by the name of the variable
2. A variable name must start with a letter or the underscore character
3. A variable name cannot start with a number
4. A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Output Variables
• The PHP echo statement is often used to output data to the screen.
• The following example will show how to output text and a variable:
• Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be
referenced/used.
• PHP has three different variable scopes:
 Local
 Global
 Static
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Global and Local Scope
• A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Example
Variable with global scope:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Variable with local scope:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP The static Keyword
• Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a
further job.
• To do this, use the static keyword when you first declare the variable:
• Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Constants in PHP
• Constants are like variables except that once they are defined they cannot be changed
or undefined.
• A constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
• A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
Note: Unlike variables, constants are automatically global across the entire script.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Create a PHP Constant
• To create a constant, use the define() function.
• Syntax
define(name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
Example
Create a constant with a case-insensitive name:
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Operators and Expressions
PHP Operators
• Operators are used to perform operations on variables and values.
• PHP divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
8. Conditional assignment operators
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by
$y
** Exponentiation $x ** $y Result of raising $x to the
$y'th power
PHP Arithmetic operators
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Assignment Operators
Assignment Same as... Description
x = y x = y The left operand gets set to the value of the
expression on the right
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
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same
type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the
same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than
zero, depending on if $x is less than, equal to, or greater
than $y. Introduced in PHP 7.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Increment / Decrement Operators
• The PHP increment operators are used to increment a variable's value.
• The PHP decrement operators are used to decrement a variable's value.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Logical Operators
Operator Name Example Result
and And $x and $y True if both $x and $y are
true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true,
but not both
&& And $x && $y True if both $x and $y are
true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP String Operators
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of
$txt1 and $txt2
.= Concatenation
assignment
$txt1 .= $txt2 Appends $txt2 to
$txt1
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Array Operators
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have
the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have
the same key/value pairs in the
same order and of the same
types
!= Inequality $x != $y Returns true if $x is not equal to
$y
<> Inequality $x <> $y Returns true if $x is not equal to
$y
!== Non-identity $x !== $y Returns true if $x is not identical
to $y
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Conditional Assignment Operators
Operator Name Example Result
?: Ternary $x
= expr1 ? e
xpr2 : expr
3
Returns the value of $x.
The value of $x
is expr2 if expr1 = TRUE.
The value of $x
is expr3 if expr1 = FALSE
?? Null coalescing $x
= expr1 ??
expr2
Returns the value of $x.
The value of $x
is expr1 if expr1 exists, and is
not NULL.
If expr1 does not exist, or is
NULL, the value of $x is expr2.
Introduced in PHP 7
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
printing data on PHP page
• The PHP print Statement
• The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print command (notice
that the text can contain HTML markup):
Example
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Control Statements- if, switch case, for, while, do while
• If
The if construct allows you to execute a piece of code if the expression provided along
with it evaluates to true.
<?php
$age = 50;
if ($age > 30)
{
echo "Your age is greater than 30!";
}
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
• Else
In the previous section, we discussed the if construct, which allows you to execute a
piece of code if the expression evaluates to true. On the other hand, if the expression
evaluates to false, it won't do anything. More often than not, you also want to execute a
different code snippet if the expression evaluates to false. That's where
the else statement comes into the picture.
if (expression)
{
// code is executed if the expression evaluates to TRUE
}
else
{
// code is executed if the expression evaluates to FALSE
}
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Switch
The switch statement is somewhat similar to the elseif statement which
we've just discussed in the previous section. The only difference is the
expression which is being checked.
In the case of the elseif statement, you have a set of different conditions, and
an appropriate action will be executed based on a condition. On the other
hand, if you want to compare a variable with different values, you can use
the switch statement.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
<?php
$favourite_site = 'Code';
switch ($favourite_site) {
case 'Business':
echo "My favourite site is business.tutsplus.com!";
break;
case 'Code':
echo "My favourite site is code.tutsplus.com!";
break;
case 'Web Design':
echo "My favourite site is webdesign.tutsplus.com!";
break;
case 'Music':
echo "My favourite site is music.tutsplus.com!";
break;
case 'Photography':
echo "My favourite site is photography.tutsplus.com!";
break;
default:
echo "I like everything at tutsplus.com!";
}
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
While Loop
The while loop is used when you want to execute a piece of code repeatedly until
the while condition evaluates to false.
while (expression)
{
// code to execute as long as expression evaluates to TRUE
}
Do-While Loop
The do-while loop is very similar to the while loop, with the only difference being that
the while condition is checked at the end of the first iteration. Thus, we can guarantee
that the loop code is executed at least once, irrespective of the result of the while
expression.
do
{
// code to execute
} while (expression);
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
For Loop
Generally, the for loop is used to execute a piece of code for a specific number of times. In
other words, if you already know the number of times you want to execute a block of code,
it's the for loop which is the best choice.
for (expr1; expr2; expr3)
{
// code to execute
}
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Initialization of an array
PHP array() Function
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Iterating through an array
PHP's fo reach loop provides a convenient way to iterate over arrays. There are two forms:
one uses both the key and value of each array entry while the other uses only the value.
First we demonstrate the key => value form:
$pets = ['Morie', 'Miki', 'Halo', 'lab' => 'Winnie'];
foreach ($pets as $key => $val) {
echo "$key => $val n";
}
/* echo output (page source view) 0 => Morie 1 => Miki 2 => Halo lab => Winnie */
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Sorting arrays
PHP - Sort Functions For Arrays
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key
• arsort() - sort associative arrays in descending order, according to the value
• krsort() - sort associative arrays in descending order, according to the key
Sort Array in Ascending Order - sort()
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
• Sort Array in Descending Order - rsort()
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
• Sort Array (Ascending Order), According to Value - asort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
• Sort Array (Ascending Order), According to Key - ksort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Sort Array (Descending Order), According to Value - arsort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Sort Array (Descending Order), According to Key - krsort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Array Functions
PHP Array Functions allow you to interact with and manipulate arrays in various ways. PHP
arrays are essential for storing, managing, and operating on sets of variables.
PHP supports simple and multi-dimensional arrays and may be either user created or
created by another function.
Installation
There is no installation needed to use PHP array functions; they are part of the PHP core
and comes alongwith standard PHP installation.
Runtime Configuration
This extension has no configuration directives defined in php.ini.
PHP Array Functions
Following table lists down all the functions related to PHP Array. Here column version
indicates the earliest version of PHP that supports the function.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Sr.No Function & Description Version
1 array()Create an array 4.2.0
2 array_change_key_case()Returns an array with all keys in lowercase or
uppercase
4.2.0
3 array_chunk()Splits an array into chunks of arrays 4.2.0
4 array_column()Return the values from a single column in the input
array
5.5.0
5 array_combine()Creates an array by using one array for keys and
another for its values
5
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
5 array_count_values()Returns an array with the number of occurrences for each
value
4
6 array_diff()Compares array values, and returns the differences 4
7 array_diff_assoc()Compares array keys and values, and returns the differences 4
8 array_diff_key()Compares array keys, and returns the
differences
5
9 array_diff_uassoc()Compares array keys and values, with an additional user-
made function check, and returns the differences
5
10 array_diff_ukey()Compares array keys, with an additional user-made function
check, and returns the differences
5
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
11 array_fill()Fills an array with values 4
12 array_fill_keys()Fill an array with values, specifying keys 5
13 array_filter()Filters elements of an array using a user-made
function
4
14 array_flip()Exchanges all keys with their associated values in
an array
4
15 array_intersect()Compares array values, and returns the
matches
4
16 array_intersect_assoc()Compares array keys and values, and
returns the matches
4
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
17 array_intersect_key()Compares array keys, and returns the matches 5
18 array_intersect_uassoc()Compares array keys and values, with an
additional user-made function check, and returns the matches
5
19 array_intersect_ukey()Compares array keys, with an additional user-
made function check, and returns the matches
5
20 array_key_exists()Checks if the specified key exists in the array 4
21 array_keys()Returns all the keys of an array 4
22 array_map()Sends each value of an array to a user-made function, which
returns new values
4
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Defining and Calling Functions
PHP Functions
PHP Built-in Functions
• A function is a self-contained block of code that performs a specific task.
• PHP has a huge collection of internal or built-in functions that you can call directly
within your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump,
etc.
PHP User-Defined Functions
• In addition to the built-in functions, PHP also allows you to define your own
functions.
• It is a way to create reusable code packages that perform specific tasks and can be
kept and maintained separately form main program.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Creating and Invoking Functions
• The basic syntax of creating a custom function can be give with:
function functionName(){
// Code to be executed
}
• The declaration of a user-defined function start with the word function, followed by
the name of the function you want to create followed by parentheses i.e. () and finally
place your function's code between curly brackets {}.
• This is a simple example of an user-defined function, that display today's date:
<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Passing by Value and passing by references
Pass by Value:
By default, PHP variables are passed by value as the function arguments in PHP. When
variables in PHP is passed by value, the scope of the variable defined at function level
bound within the scope of function. Changing either of the variables doesn’t have any
effect on either of the variables.
Example:
<?php
// Function used for assigning new
// value to $string variable and
// printing it
function print_string( $string ) {
$string = "Function geeksforgeeks"."n";
// Print $string variable
print($string);
}
// Driver code
$string = "Global geeksforgeeks"."n";
print_string($string);
print($string);
?>
Output:
Function geeksforgeeks
Global geeksforgeeks
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Pass by reference: When variables are passed by reference, use & (ampersand) symbol
need to be added before variable argument. For example: function( &$x ). Scope of both
global and function variable becomes global as both variables are defined by same
reference. Therefore, whenever global variable is change, variable inside function also gets
changed and vice-versa is applicable.
Example:
<?php
// Function used for assigning new value to
// $string variable and printing it
function print_string( &$string ) {
$string = "Function geeksforgeeks n";
// Print $string variable
print( $string );
}
// Driver code
$string = "Global geeksforgeeks n";
print_string( $string );
print( $string );
?>
Output:
Function geeksforgeeks
Function geeksforgeeks
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Built in Functions
These built in functions are what make PHP a very efficient and productive scripting
language.
The built in functions can be classified into many categories. Below is the list of the
categories.
String Functions
• These are functions that manipulate string data, refer to the article on strings for
implementation examples of string functions
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.
Date Function
• The date function is used to format Unix date and time to human readable format.
• Other functions These include;
• Arrays – see the article on arrays for examples
• Files – see the article on files for examples
• Database functions – see the article on MySQL PHP and other database access
methods v2
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
BCA
Semester: FIFTH Semester
Name of the Subject:
WEB BASED PROGRAMMING (PHP)
Unit-3
FACULTY NAME: Ms.Rekha Jain
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
UNIT-2
Working with Forms
Get and Post Methods
There are two ways the browser client can send information to the web server.
• The GET Method
• The POST Method
Before the browser sends the information, it encodes it using a scheme called URL
encoding. In this scheme, name/value pairs are joined with equal signs and different pairs
are separated by the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric
characters are replaced with a hexadecimal values. After the information is encoded it is
sent to the server.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
The GET Method
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
• The GET method produces a long string that appears in your server logs, in the
browser's Location: box.
• The GET method is restricted to send upto 1024 characters only.
• Never use GET method if you have password or other sensitive information to be
sent to the server.
• GET can't be used to send binary data, like images or word documents, to the
server.
• The data sent by GET method can be accessed using QUERY_STRING environment
variable.
• The PHP provides $_GET associative array to access all the sent information using
GET method.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
The POST Method
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
• The POST method does not have any restriction on data size to be sent.
• The POST method can be used to send ASCII as well as binary data.
• The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
• The PHP provides $_POST associative array to access all the sent information using POST
method.
The $_REQUEST variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Query string
• The information can be sent across the web pages. This information is called query string.
• This query string can be passed from one page to another by appending it to the address of
the page.
• You can pass more than one query string by inserting the & sign between the query strings.
• A query string can contain two things:
 the query string ID
 and its value.
• The query string passed across the web pages is stored in $_REQUEST, $_GET, or $_POST
variable.
• Whether you passed the query string by using GET or POST method, it is stored in
$_REQUEST variable.
• You should note that whether the query string is passed by the GET or POST method it can be
accessed by using the $_REQUEST variable.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
HTML form controls and PHP
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit
button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
When the user fills out the form above and clicks the submit button, the form data is sent
for processing to a PHP file named "welcome.php". The form data is sent with the HTTP
POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
The output could be something like this:
Welcome John
Your email address is john.doe@example.com
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Maintaining User State
HTTP is a stateless protocol which means every user request is processed independently
and it has nothing to do with the requests processed before it. Hence there is no way to
store or send any user specific details using HTTP protocol.
But in modern applications, user accounts are created and user specific information is
shown to different users, for which we need to have knowledge about who the user(or
what he/she wants to see etc) is on every webpage.
PHP provides for two different techniques for state management of your web application,
they are:
• Server Side State Management
• Client Side Server Management
Client Side State Management
In client side state management the user specific information is stored at the client side
i.e. in the bowser. Again, this information is available on all the webpages of the web
application.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Cookies
• Cookie is a small piece of information stored as a file in the user's browser by the web
server. Once created, cookie is sent to the web server as header information with every
HTTP request.
• You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.
Realworld Use of Cookies
 To store user information like when he/she visited, what pages were visited on the
website etc, so that next time the user visits your website you can provide a better
user experience.
 To store basic website specific information to know this is not the first visit of user.
 You can use cookies to store number of visits or view counter.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Types of Cookies
There are two types of cookies, they are:
• Session Cookie: This type of cookies are temporary and are expire as soon as the
session ends or the browser is closed.
• Persistent Cookie: To make a cookie persistent we must provide it with an expiration
time. Then the cookie will only expire after the given expiration time, until then it will
be a valid cookie.
Creating a Cookie in PHP
• In PHP we can create/set a cookie using the setcookie() function.
Syntax:
setcookie(name, value, expire, path, domain, secure)
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Argument What is it for?
name Used to specify the name of the cookie. It is a mandatory argument. Name of the
cookie must be a string.
value Used to store any value in the cookie. It is generally saved as a pair with name. For
example, name is userid and value is 7007, the userid for any user.
expire Used to set the expiration time for a cookie. if you do not provide any value, the
cookie will be treated as a session cookie and will expire when the browser is closed.
path Used to set a web URL in the cookie. If set, the cookie will be accessible only from that
URL. To make a cookie accessible through a domain, set '/' as cookie path.
domain The domain of your web application. It can be used to limit access of cookie for sub-
domains. For example, if you set the domain value as wwww.studytonight.com, then
the cookie will be inaccessible from blog.studytonight.com
secure If you set this to 1, then the cookie will be available and sent only over HTTPS
connection.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
So if we want to create a cookie to store the name of the user who visited your website,
and set an expiration time of a week, then we can do it like this,
<?php
setcookie("username", "iamabhishek", time()+60*60*24*7);
?>
Updating Cookie in PHP
To update/modify a cookie, simply set it again. For example, if we want to update the
username stored in the cookie created above, we can do it using setcookie() method
again,
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else { echo "cookie not set!"; }
?>
</body>
</html>
We just update the value of username cookie from iamabhishek to iamNOTabhishek.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Delete a Cookie in PHP
To delete/remove a cookie, we need to expire the cookie, which can be done by updating
the cookie using the setcookie() function with expiration date in past.
<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time() - 3600);
?> <html>
<body>
<?php
echo "cookie username is deleted!";
?>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Sessions
• To store information accessible accross web pages, we use sessions. Session is not
stored on the user browser like cookie, hence it is a more secure option.
• When a user logs into their account on any web application, a session is created for
them, and in the session their username or userid or some other unique identifier is
stored, which is then used on the consecutive webpages to show information specific to
that user. On logout, the session is destroyed.
• Session is not limited by any size limit, you can store any information in the session,
irrespective of its size.
Realworld Use of Session
• Web applications which require a user to login, use session to store user information, so
that on every webpage related information can be displayed to the user.
• In eCommerce websotes, shopping cart is geberally saved as part of session.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Start a Session in PHP
• In PHP we can start a session by using the session_start() function. And data is stored in
the session using session variable, which can be assigned different values using global
variable $_SESSION
• In simpler words, using the function session_start() we initialize the session, in which we
can store information using the session variable $_SESSION.
Let's take an example, below we have a webpage with Php file named first_page.php
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
<?php
// start the session
session_start();
// set the session variable
$_SESSION["username"] = "iamabhishek";
$_SESSION["userid"] = "1";
?>
<html>
<body>
<?php
echo "Session variable is set.";
?>
<a href="second_page.php">Go to Second Page</a>
</body>
</html>
NOTE: The function session_start() should be the first statement of the page, before any
HTML tag.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Getting PHP Session Variable Values
In the code above, we have started a session and set two session variables. Above
webpage will also have a link to navigate to Second page second_page.php.
Below is the code for second_page.php, in which we fetch values from the session
variable which are set in the first_page.php.
<?php
// start the session
session_start();
// get the session variable values
$username = $_SESSION["username"];
$userid = $_SESSION["userid"];
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid; ?>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Update Session Variable in PHP
To update any value stored in the session variable, start the session by
calling session_start() function and then simply overwrite the vakue to update session
variable.
<?php
// start the session
session_start();
// update the session variable values
$_SESSION["userid"] = "1111";
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Destroy a Session in PHP
To clean the session variable or to remove all the stored values from the session variable
we can use the function session_unset() and to detroy the session, we
use session_destroy() function.
<?php
// start the session
session_start();
?>
<html>
<body>
<?php
// clean the session variable
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Working With Files
Opening and Closing Files
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function gives you more options than
the readfile() function.
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the
file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't
exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the
file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file
doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Read File - fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
The fclose() function is used to close an open file.
The fclose() requires the name of the file (or a variable that holds the filename) we want
to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Read Single Line - fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the "webdictionary.txt" file:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Reading and Writing to Files
Reading a file
• Once a file is opened using fopen() function it can be read with a function
called fread().
• This function requires two arguments.
• These must be the file pointer and the length of the file expressed in bytes.
• The files length can be found using the filesize() function which takes the file name as
its argument and returns the size of the file expressed in bytes.
• ]So here are the steps required to read a file with PHP.
 Open a file using fopen() function.
 Get the file's length using filesize() function.
 Read the file's content using fread() function.
 Close the file with fclose() function.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
The following example assigns the content of a text file to a variable then displays those
contents on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>
<?php $filename = "tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" ); ?>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Writing a file
• A new file can be written or text can be appended to an existing file using the
PHP fwrite() function.
• This function requires two arguments specifying a file pointer and the string of data
that is to be written.
• Optionally a third integer argument can be included to specify the length of the data to
write.
• If the third argument is included, writing would will stop after the specified length has
been reached.
The following example creates a new text file then writes a short text heading inside it.
After closing this file its existence is confirmed using file_exist() function which takes file
name as an argument
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple testn" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
} $filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "$filetext" );
echo("file name: $filename");
?>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Getting Information on Files
As a Web developer, it's common to have to interact with files on disk: check disk usage,
read file permissions, find file modification times, and read file contents.
Fortunately PHP comes with a full-fledged set of file functions for just this purpose and
this document lists them all, together with usage examples (See Table A). Keep reading,
you might discover something new!
Function Explanation Example
filesize($file) This function returns the size of a
file, in bytes. It's useful to calculate
how much space a file occupies on
disk.
<?php
// get file size in bytes
echo "Size is " . filesize('myfile.html') . "
bytes";
?>
fileowner($file)
filegroup($file)
These functions return the owner
and group ID for a file. They're useful
to find out who "owns" a particular
file.
<?php
// get file owner and group
echo "UID: " . fileowner('myfile.html');
echo "GID: " . filegroup('myfile.html');
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
fileatime($file)
filemtime($file)
These functions return a timestamp
indicating when a file was last accessed and
modified respectively. They're useful to find
out if a file has changed since a particular
date.
<?php
// get file access/modification times
echo "Last accessed on: " . date("d-m-y",
fileatime('myfile.html'));
echo "Last modified on: " . date("d-m-y",
filemtime('myfile.html'));
?>
fileperms($file) This function returns the permissions of a
file. Use it to check if a file is readable,
writable or executable.
<?php
// get permissions in octal format
echo "File permissions: " . sprintf('%o',
fileperms('myfile.html'));
?>
filetype($file) This function returns the "type" of a file -
whether link, directory, character or block
device, or regular file. Use this to test the
nature of a file before using it in an
operation.
<?php
// get file type
echo "File type: " . filetype('myfile.html');
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
stat($file) This function is a "catch all" function that returns
detailed statistics about a file, including its owner
and group, size, time of last change, block usage
and inode number. Use this function instead of
the functions listed previously if you need to
obtain complete file statistics in a single call.
<?php
// get file statistics
print_r(stat('myfile.html'));
?>
realpath($f
ile)
This function turns a relative file path into an
absolute path. It's useful when you need to find
out exactly where a file is located on disk.
<?php
// get absolute path
// returns "/tmp/myfile.html"
echo "File path: " .
realpath("./cook/book/../../myfile.html");
?>
basename(
$file)
dirname($
path)
Given a complete file path, these functions can
split it into its constituent parts and separately
return the file name and directory name
respectively.
<?php
// split directory and file names
// returns "/usr/local/bin"
echo "Directory: " . dirname("/usr/local/bin/php");
// returns "php"
echo "File: " . basename("/usr/local/bin/php");
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
file($file) This function reads the contents of
a file into an array. Each element of
the array represents one line of the
file. This function is useful to read a
file's contents into a variable, so
that it can be processed further.
<?php
// read file contents
$lines = file('myfile.html');
// print line by line
for($x=1; $x<=sizeof($lines); $x++) {
echo "Line $x: " . $lines[$x-1] .
"n";
}
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
BCA
Semester: FIFTH Semester
Name of the Subject:
WEB BASED PROGRAMMING (PHP)
Unit-4
FACULTY NAME: Ms.Rekha Jain
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
PHP Database connectivity
Introduction to MYSQL
What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the
most popular database system used with PHP. MySQL is developed, distributed, and
supported by Oracle Corporation.
The data in a MySQL database are stored in tables which consists of columns and rows.
• MySQL is a database system that runs on a server.
• MySQL is ideal for both small and large applications.
• MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
• MySQL compiles on a number of platforms.
How to connect PHP with MySQL Database?
PHP 5 and later can work with a MySQL database using:
• MySQLi extension.
• PDO (PHP Data Objects).
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Connecting to a database
There are 3 ways in which we can connect to MySQl from PHP as listed above and described below:
1. Using MySQLi object-oriented procedure: We can use the MySQLi object-oriented procedure to
establish a connection to MySQL database from a PHP script.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully"; ?>
OUTPUT:
Connected successfully
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
2. Using MySQLi procedural procedure : There is also a procedural approach of MySQLi
to establish a connection to MySQL database from a PHP script as described below.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfuly";
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
3. Using PDO procedure: PDO stands for PHP Data Objects. That is, in this method we
connect to the database using data objects in PHP as described below:
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Closing A Connection
When we establish a connection to MySQL database from a PHP script , we should also
disconnect or close the connection when our work is finished. Here we have described
the syntax of closing the connection to a MySQL database in all 3 methods described
above. We have assumed that the reference to the connection is stored in $conn
variable.
• Using MySQLi object oriented procedure
Syntax$conn->close();
• Using MySQLi procedural procedure
Syntaxmysqli_close($conn);
• Using PDO procedure
Syntax$conn = null;
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Use a particular database
It is very simple to select a database from the mysql> prompt. You can use the SQL
command use to select a database.
Here is an example to select a database called TUTORIALS −
[root@host]# mysql -u root -p
Enter password:******
mysql> use TUTORIALS;
Database changed
mysql>
Selecting a MySQL Database Using PHP Script
PHP provides function mysql_select_db to select a database. It returns TRUE on success or
FALSE on failure.
Syntax
bool mysql_select_db( db_name, connection );
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Example
Here is an example showing you how to select a database.
<html>
<head>
<title>Selecting MySQL Database</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully'; mysql_select_db( 'TUTORIALS' );
mysql_close($conn);
?>
</body>
</html>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Sending query to database
PHP mysqli query() Function
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// Perform query
if ($result = $mysqli -> query("SELECT * FROM Persons")) {
echo "Returned rows are: " . $result -> num_rows;
// Free result set
$result -> free_result();
}
$mysqli -> close();
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Definition and Usage
The query() / mysqli_query() function performs a query against a database.
Syntax
• Object oriented style:
$mysqli -> query(query, resultmode)
• Procedural style:
mysqli_query(connection, query, resultmode)
Parameter Description
connection Required. Specifies the MySQL connection to use
query Required. Specifies the SQL query string
resultmode Optional. A constant. Can be one of the following:
•MYSQLI_USE_RESULT (Use this to retrieve large amount of data)
•MYSQLI_STORE_RESULT (This is defaul
Parameter Values:
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Parsing of the query results
Query Processing includes translations on high level Queries into low level expressions
that can be used at physical level of file system, query optimization and actual execution
of query to get the actual result.
Block Diagram of Query Processing is as:
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Detailed Diagram is drawn as:
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
It is done in the following steps:
Step-1:
Parser: During parse call, the database performs the following checks- Syntax check,
Semantic check and Shared pool check, after converting the query into relational
algebra.Parser performs the following checks as (refer detailed diagram):
• Syntax check – concludes SQL syntactic validity. Example:SELECT * FORM
employee Here error of wrong spelling of FROM is given by this check.
• Semantic check – determines whether the statement is meaningful or not.
Example: query contains a tablename which does not exist is checked by this
check.
• Shared Pool check – Every query possess a hash code during its execution. So, this
check determines existence of written hash code in shared pool if code exists in
shared pool then database will not take additional steps for optimization and
execution.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Hard Parse and Soft Parse –
If there is a fresh query and its hash code does not exist in shared pool then that query has
to pass through from the additional steps known as hard parsing otherwise if hash code
exists then query does not passes through additional steps. It just passes directly to
execution engine (refer detailed diagram). This is known as soft parsing.
Hard Parse includes following steps – Optimizer and Row source generation.
Step-2:
Optimizer: During optimization stage, database must perform a hard parse atleast for one
unique DML statement and perform optimization during this parse. This database never
optimizes DDL unless it includes a DML component such as subquery that require
optimization.It is a process in which multiple query execution plan for satisfying a query
are examined and most efficient query plan is satisfied for execution.
Database catalog stores the execution plans and then optimizer passes the lowest cost
plan for execution.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Row Source Generation –
The Row Source Generation is a software that receives a optimal execution plan from the
optimizer and produces an iterative execution plan that is usable by the rest of the
database. the iterative plan is the binary program that when executes by the sql engine
produces the result set.
Step-3:
Execution Engine: Finally runs the query and display the required result.
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Checking data errors
PHP mysqli error() Function
Example - Object Oriented style
Return the last error description for the most recent function call, if any:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// Perform a query, check for error
if (!$mysqli -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) {
echo("Error description: " . $mysqli -> error);
}
$mysqli -> close();
?>
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Definition and Usage
The error / mysqli_error() function returns the last error description for the most recent
function call, if any.
Syntax
• Object oriented style:
$mysqli -> error
• Procedural style:
mysqli_error(connection)
Parameter Description
connection Required. Specifies the MySQL connection to use
Parameter Values
Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Example - Procedural Oriented style
Return the last error description for the most recent function call, if any:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) {
echo("Error description: " . mysqli_error($con));
}
mysqli_close($con);
?>

More Related Content

What's hot (20)

Java package
Java packageJava package
Java package
 
Applets
AppletsApplets
Applets
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
I. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHMI. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHM
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Linq
LinqLinq
Linq
 
jstl ( jsp standard tag library )
jstl ( jsp standard tag library )jstl ( jsp standard tag library )
jstl ( jsp standard tag library )
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
ProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) IntroductionProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) Introduction
 
Xml
XmlXml
Xml
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycle
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Introduction to prolog
Introduction to prologIntroduction to prolog
Introduction to prolog
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
 

Similar to PHP Web Programming Course Documents

Similar to PHP Web Programming Course Documents (20)

Computer Applications
Computer ApplicationsComputer Applications
Computer Applications
 
Ahbab a
Ahbab aAhbab a
Ahbab a
 
Chandra Akhilesh
Chandra AkhileshChandra Akhilesh
Chandra Akhilesh
 
Ramji
RamjiRamji
Ramji
 
Computer Applications
Computer ApplicationsComputer Applications
Computer Applications
 
resume_prerit
resume_preritresume_prerit
resume_prerit
 
Introduction To Database Management System
Introduction To Database Management SystemIntroduction To Database Management System
Introduction To Database Management System
 
Fundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersFundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-Developers
 
Fullstack Interview Questions and Answers.pdf
Fullstack Interview Questions and Answers.pdfFullstack Interview Questions and Answers.pdf
Fullstack Interview Questions and Answers.pdf
 
yogesh_surve_resume
yogesh_surve_resumeyogesh_surve_resume
yogesh_surve_resume
 
Anil_Java_3yrsSE
Anil_Java_3yrsSEAnil_Java_3yrsSE
Anil_Java_3yrsSE
 
Module 2 introduction to a web-app
Module 2  introduction to a web-appModule 2  introduction to a web-app
Module 2 introduction to a web-app
 
Resume_Anand_Vikram
Resume_Anand_VikramResume_Anand_Vikram
Resume_Anand_Vikram
 
Ranjeet Mishra_JAVA_3+year exp
Ranjeet Mishra_JAVA_3+year expRanjeet Mishra_JAVA_3+year exp
Ranjeet Mishra_JAVA_3+year exp
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
 
E commerce
E commerce E commerce
E commerce
 
Yahya Resume
Yahya ResumeYahya Resume
Yahya Resume
 
Abhilash_Documentum
Abhilash_Documentum Abhilash_Documentum
Abhilash_Documentum
 
Abhilash_Documentum
Abhilash_Documentum Abhilash_Documentum
Abhilash_Documentum
 
DO WHATEVER JUT TO STAY ALIVE
DO WHATEVER JUT TO STAY ALIVEDO WHATEVER JUT TO STAY ALIVE
DO WHATEVER JUT TO STAY ALIVE
 

More from cpjcollege

Tax Law (LLB-403)
Tax Law (LLB-403)Tax Law (LLB-403)
Tax Law (LLB-403)cpjcollege
 
Law and Emerging Technology (LLB -405)
 Law and Emerging Technology (LLB -405) Law and Emerging Technology (LLB -405)
Law and Emerging Technology (LLB -405)cpjcollege
 
Law of Crimes-I ( LLB -205)
 Law of Crimes-I  ( LLB -205)  Law of Crimes-I  ( LLB -205)
Law of Crimes-I ( LLB -205) cpjcollege
 
Socio-Legal Dimensions of Gender (LLB-507 & 509 )
Socio-Legal Dimensions of Gender (LLB-507 & 509 )Socio-Legal Dimensions of Gender (LLB-507 & 509 )
Socio-Legal Dimensions of Gender (LLB-507 & 509 )cpjcollege
 
Family Law-I ( LLB -201)
Family Law-I  ( LLB -201) Family Law-I  ( LLB -201)
Family Law-I ( LLB -201) cpjcollege
 
Alternative Dispute Resolution (ADR) [LLB -309]
Alternative Dispute Resolution (ADR) [LLB -309] Alternative Dispute Resolution (ADR) [LLB -309]
Alternative Dispute Resolution (ADR) [LLB -309] cpjcollege
 
Law of Evidence (LLB-303)
Law of Evidence  (LLB-303) Law of Evidence  (LLB-303)
Law of Evidence (LLB-303) cpjcollege
 
Environmental Studies and Environmental Laws (: LLB -301)
Environmental Studies and Environmental Laws (: LLB -301)Environmental Studies and Environmental Laws (: LLB -301)
Environmental Studies and Environmental Laws (: LLB -301)cpjcollege
 
Code of Civil Procedure (LLB -307)
 Code of Civil Procedure (LLB -307) Code of Civil Procedure (LLB -307)
Code of Civil Procedure (LLB -307)cpjcollege
 
Constitutional Law-I (LLB -203)
 Constitutional Law-I (LLB -203) Constitutional Law-I (LLB -203)
Constitutional Law-I (LLB -203)cpjcollege
 
Women and Law [LLB 409 (c)]
Women and Law [LLB 409 (c)]Women and Law [LLB 409 (c)]
Women and Law [LLB 409 (c)]cpjcollege
 
Corporate Law ( LLB- 305)
Corporate Law ( LLB- 305)Corporate Law ( LLB- 305)
Corporate Law ( LLB- 305)cpjcollege
 
Human Rights Law ( LLB -407)
 Human Rights Law ( LLB -407) Human Rights Law ( LLB -407)
Human Rights Law ( LLB -407)cpjcollege
 
Labour Law-I (LLB 401)
 Labour Law-I (LLB 401) Labour Law-I (LLB 401)
Labour Law-I (LLB 401)cpjcollege
 
Legal Ethics and Court Craft (LLB 501)
 Legal Ethics and Court Craft (LLB 501) Legal Ethics and Court Craft (LLB 501)
Legal Ethics and Court Craft (LLB 501)cpjcollege
 
Political Science-II (BALLB- 209)
Political Science-II (BALLB- 209)Political Science-II (BALLB- 209)
Political Science-II (BALLB- 209)cpjcollege
 
Health Care Law ( LLB 507 & LLB 509 )
Health Care Law ( LLB 507 & LLB 509 )Health Care Law ( LLB 507 & LLB 509 )
Health Care Law ( LLB 507 & LLB 509 )cpjcollege
 
Land and Real Estate Laws (LLB-505)
Land and Real Estate Laws (LLB-505)Land and Real Estate Laws (LLB-505)
Land and Real Estate Laws (LLB-505)cpjcollege
 
Business Environment and Ethical Practices (BBA LLB 213 )
Business Environment and Ethical Practices (BBA LLB 213 )Business Environment and Ethical Practices (BBA LLB 213 )
Business Environment and Ethical Practices (BBA LLB 213 )cpjcollege
 
HUMAN RESOURCE MANAGEMENT (BBA LLB215 )
HUMAN RESOURCE MANAGEMENT (BBA LLB215 )HUMAN RESOURCE MANAGEMENT (BBA LLB215 )
HUMAN RESOURCE MANAGEMENT (BBA LLB215 )cpjcollege
 

More from cpjcollege (20)

Tax Law (LLB-403)
Tax Law (LLB-403)Tax Law (LLB-403)
Tax Law (LLB-403)
 
Law and Emerging Technology (LLB -405)
 Law and Emerging Technology (LLB -405) Law and Emerging Technology (LLB -405)
Law and Emerging Technology (LLB -405)
 
Law of Crimes-I ( LLB -205)
 Law of Crimes-I  ( LLB -205)  Law of Crimes-I  ( LLB -205)
Law of Crimes-I ( LLB -205)
 
Socio-Legal Dimensions of Gender (LLB-507 & 509 )
Socio-Legal Dimensions of Gender (LLB-507 & 509 )Socio-Legal Dimensions of Gender (LLB-507 & 509 )
Socio-Legal Dimensions of Gender (LLB-507 & 509 )
 
Family Law-I ( LLB -201)
Family Law-I  ( LLB -201) Family Law-I  ( LLB -201)
Family Law-I ( LLB -201)
 
Alternative Dispute Resolution (ADR) [LLB -309]
Alternative Dispute Resolution (ADR) [LLB -309] Alternative Dispute Resolution (ADR) [LLB -309]
Alternative Dispute Resolution (ADR) [LLB -309]
 
Law of Evidence (LLB-303)
Law of Evidence  (LLB-303) Law of Evidence  (LLB-303)
Law of Evidence (LLB-303)
 
Environmental Studies and Environmental Laws (: LLB -301)
Environmental Studies and Environmental Laws (: LLB -301)Environmental Studies and Environmental Laws (: LLB -301)
Environmental Studies and Environmental Laws (: LLB -301)
 
Code of Civil Procedure (LLB -307)
 Code of Civil Procedure (LLB -307) Code of Civil Procedure (LLB -307)
Code of Civil Procedure (LLB -307)
 
Constitutional Law-I (LLB -203)
 Constitutional Law-I (LLB -203) Constitutional Law-I (LLB -203)
Constitutional Law-I (LLB -203)
 
Women and Law [LLB 409 (c)]
Women and Law [LLB 409 (c)]Women and Law [LLB 409 (c)]
Women and Law [LLB 409 (c)]
 
Corporate Law ( LLB- 305)
Corporate Law ( LLB- 305)Corporate Law ( LLB- 305)
Corporate Law ( LLB- 305)
 
Human Rights Law ( LLB -407)
 Human Rights Law ( LLB -407) Human Rights Law ( LLB -407)
Human Rights Law ( LLB -407)
 
Labour Law-I (LLB 401)
 Labour Law-I (LLB 401) Labour Law-I (LLB 401)
Labour Law-I (LLB 401)
 
Legal Ethics and Court Craft (LLB 501)
 Legal Ethics and Court Craft (LLB 501) Legal Ethics and Court Craft (LLB 501)
Legal Ethics and Court Craft (LLB 501)
 
Political Science-II (BALLB- 209)
Political Science-II (BALLB- 209)Political Science-II (BALLB- 209)
Political Science-II (BALLB- 209)
 
Health Care Law ( LLB 507 & LLB 509 )
Health Care Law ( LLB 507 & LLB 509 )Health Care Law ( LLB 507 & LLB 509 )
Health Care Law ( LLB 507 & LLB 509 )
 
Land and Real Estate Laws (LLB-505)
Land and Real Estate Laws (LLB-505)Land and Real Estate Laws (LLB-505)
Land and Real Estate Laws (LLB-505)
 
Business Environment and Ethical Practices (BBA LLB 213 )
Business Environment and Ethical Practices (BBA LLB 213 )Business Environment and Ethical Practices (BBA LLB 213 )
Business Environment and Ethical Practices (BBA LLB 213 )
 
HUMAN RESOURCE MANAGEMENT (BBA LLB215 )
HUMAN RESOURCE MANAGEMENT (BBA LLB215 )HUMAN RESOURCE MANAGEMENT (BBA LLB215 )
HUMAN RESOURCE MANAGEMENT (BBA LLB215 )
 

Recently uploaded

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 

Recently uploaded (20)

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 

PHP Web Programming Course Documents

  • 1. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) BCA Semester: FIFTH Semester Name of the Subject: WEB BASED PROGRAMMING (PHP) Unit-1 FACULTY NAME: Ms.Rekha Jain
  • 2. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) UNIT-1 INTRODUCTION TO WEB APPLICATIONS The term web application refers to a software system that provides a user interface through a web browser. Examples of web applications include blogs, online shopping, search engines, etc. Static web pages are stored in the file system of web server usually displays the same information to all visitors. Whereas dynamic pages are constructed by a program that produce the HTML. This type of web application provide individual information to the user and let them personalize the content according to their preferences.
  • 3. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) ABOUT HTML HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages. This language is used to annotate (make notes for the computer) text so that a machine can understand it and manipulate text accordingly. Most of markup (e.g. HTML) languages are human readable. Language uses tags to define what manipulation has to be done on the text. HTML is a markup language which is used by the browser to manipulate text, images and other content to display it in required format. HTML was created by Tim Berners-Lee in 1991. The first ever version of HTML was HTML 1.0 but the first standard version was HTML 2.0 which was published in 1999.
  • 4. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Client Side Scripting Vs Server Side Scripting A script is generally a series of program or instruction, which has to be executed on other program or application. The scripts can be written in two forms, at the server end (back end) or at the client end (server end). Basis for comparison SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING Basic Works in the back end which could not be visible at the client end. Works at the front end and script are visible among the users. Processing Requires server interaction. Does not need interaction with the server.
  • 5. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Languages involved PHP, ASP.net, Ruby on Rails, ColdFusion, Python, etcetera. HTML, CSS, JavaScript, etc. Affect Could effectively customize the web pages and provide dynamic websites. Can reduce the load to the server. Security Relatively secure. Insecure
  • 6. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Conclusion: Client-side scripting and server-side scripting works in a coordinated manner with each other. However, both the scripting techniques are very different, where the client-side scripting emphasize on making the interface of the web application or website more appealing and functional. Conversely, server-side scripting emphasizes on the data accessing methods, error handling and fast processing etc.
  • 7. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) LOCAL SERVER AND REMOTE SERVER Understanding the difference between a Local Server and a Remote server is very important. If you are referring to a Local Server, this means that you have a server setup on your current machine. When the server is Remote, this just means that it is on another computer. You may have heard the phrase, "Working Remotely." What this means is that the person will not be working in the office, instead they could be working at home or from their favorite corner coffee shop. So since that person is away from the office, they are considered "Remote." In the same case if a server hosting your files is not in-house or on your computer, it is considered to be a Remote Server.
  • 8. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) LOCAL SERVER AND REMOTE SERVER First let's talk about what happens when you visit a web page in your browser. Well, your computer needs to contact a (remote) server on the web and then send the data back to your computer:
  • 9. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) LOCAL SERVER AND REMOTE SERVER But when you are running a local server, your computer contacts itself since it is running a local server and returns the data back to the browser:
  • 10. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) INSTALLING WEB SERVERS Web server is a computer where the web content is stored. Basically web server is used to host the web sites but there exists other web servers also such as gaming, storage, FTP, email etc.
  • 11. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) and Personal Web Server(PWS) What is IIS - Internet Information Server ? • Internet Information Server (IIS) is one of the most popular web servers from Microsoft that is used to host and provide Internet-based services to ASP.NET and ASP Web applications. • A web server is responsible for providing a response to requests that come from users. • When a request comes from client to server IIS takes that request from users and process it and send response back to users. • Internet Information Server (IIS) has it's own ASP.NET Process Engine to handle the ASP.NET request.
  • 12. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) and Personal Web Server(PWS) Internet Information Server • This basic functionality allows web servers to share and deliver information across local area networks (LAN), such as corporate intranets, and wide area networks (WAN), such as the internet. • A web server can deliver information to users in several forms, such as static webpages coded in HTML; through file exchanges as downloads and uploads; and text documents, image files and more.
  • 13. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) IIS 5.0 – Enterprise-level Web server – Included with Windows 2000 – Allows computer to serve documents • Internet Services Manager (Fig. 1.1) – Open Control Panel, double click Administrative Tools icon, then double click Internet Services Manager icon – Administration program for IIS – Place documents to be requested in default directory or virtual directory • Default: C:InetpubWwwroot • Virtual: alias for existing directory on local machine
  • 14. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) F.g. 1.1 Internet Services Manager dialog
  • 15. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) • Default FTP Site and Default Web Site – Permit transferring documents between computer and server – HTTP used frequently to request documents • Default SMTP Virtual Server – Allows for creation of mail server • Create virtual directory in Default Web Site – Most Web documents reside in Webpub directory • Right click Webpub, select New, then Virtual Directory • Initiates Virtual Directory Creation Wizard (Fig. 1.2) – Guides user through virtual directory creation process
  • 16. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) F.g. 1.2 Virtual Directory Creation Wizard welcome dialog
  • 17. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) • Virtual Directory Alias (Fig. 1.3) – Enter name for virtual directory • Name should not conflict with an existing virtual directory • Web Site Content Directory (Fig. 1.4) – Enter path of directory containing Web documents • Access Permissions (Fig. 1.5) – Presents security level choices – Select access level appropriate for Web document
  • 18. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) F.g.1.3 Virtual Directory Alias dialog.
  • 19. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) F.g. 1.4 Web Site Content Directory dialog.
  • 20. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) • Access Permissions (Fig. 1.5) – Presents security level choices – Select access level appropriate for Web document – Read allows users to read and download files – Run Scripts allows scripts to run in directory – Execute allows applications to run in directory – Write allows Web page to accept user input – Browse allows users to navigate between documents – Read and Run Scripts selected by default
  • 21. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) F.g. 1.5 Access Permissions dialog Internet Information Server(IIS)
  • 22. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) and Personal Web Server(PWS) What is Personal Web Server (PWS) ? • Personal Web Server (PWS) is a web server application from Microsoft that allows a user to save, selectively publish and share posts on the World Wide Web or a local network. • Personal Web Server differs from all other types of Web servers in the way that it is controlled and operated by an individual rather than a company. • PWS can be used to support Web pages if it is attached to a continuous Internet connection. • It can also help websites to generate more traffic in an offline mode by staging websites before they are published globally.
  • 23. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Internet Information Server(IIS) and Personal Web Server(PWS) Installing Microsoft Personal Web Server The nice thing about Microsoft Personal Web Servers is that it is a free download from the Microsoft web site at http://www.microsoft.com/windows/ie/pws/. It is a very easy install. After you download the software, you will have an executable installation file. When you click on the file to install, it will not prompt you for installation questions. It simply installs where it wants to on your C drive. After the software is installed, it requires a reboot of your system. After the system reboot, the PWS icon will be running in the System tray, and it will also add an icon to your Control Panel. From either location, you can access configuration settings to customize and configure PWS for your needs. The HTTP process starts by default, but if you want to run the FTP process, you will have to configure it to start up automatically.
  • 24. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Static website vs Dynamic website development Static website Static website is the basic type of website that is easy to create. You don't need the knowledge of web programming and database design to create a static website. Its web pages are coded in HTML. The codes are fixed for each page so the information contained in the page does not change and it looks like a printed page.
  • 25. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Static website vs Dynamic website development Dynamic website Dynamic website is a collection of dynamic web pages whose content changes dynamically. It accesses content from a database or Content Management System (CMS). Therefore, when you alter or update the content of the database, the content of the website is also altered or updated.
  • 26. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Static Website Dynamic Website Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly. It uses the HTML code for developing a website. It uses the server side languages such as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website. It sends exactly the same response for every request. It may generate different HTML for each of the request. The content is only changed when someone publishes and updates the file (sends it to the web server). The page contains "server-side" code which allows the server to generate the unique content when the page is loaded. Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage of dynamic website. Static website vs Dynamic website development.
  • 27. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) BCA Semester: FIFTH Semester Name of the Subject: WEB BASED PROGRAMMING (PHP) Unit-2 FACULTY NAME: Ms.Rekha Jain
  • 28. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) UNIT-2 INTRODUCTION TO PHP PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994. • PHP is a recursive acronym for "PHP: Hypertext Preprocessor". • PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. • It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. • PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
  • 29. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) INTRODUCTION TO PHP • PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time. • PHP Syntax is C-Like. • PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user.
  • 30. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) INTRODUCTION TO PHP Characteristics of PHP: Five important characteristics make PHP's practical nature possible − • Simplicity • Efficiency • Security • Flexibility • Familiarity
  • 31. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Example of php script: As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML you'll have PHP statements like this − <html> <head> <title>Hello World</title> </head> <body> <?php echo "Hello, World!";?> </body> </html> It will produce following result − Hello, World!
  • 32. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Start and End tags of PHP The PHP syntax is a set of rules that define how a program should be written. All code written in PHP must be identified as PHP code. A set of tags are used to mark the beginning and end of a block of code, in between which any amount of code can be written. • The standard opening tag is: <?php • The standard closing tag is: ?> Note: PHP statements end with a semicolon (;).
  • 33. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Data types in PHP Variables can store data of different types, and different data types can do different things. PHP supports the following data types: • String • Integer • Float (floating point numbers - also called double) • Boolean • Array • Object • NULL
  • 34. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP String • A string is a sequence of characters, like "Hello world!". • A string can be any text inside quotes. You can use single or double quotes: $x = "Hello world!"; $y = 'Hello world!'; PHP Integer • An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. • Rules for integers: • An integer must have at least one digit • An integer must not have a decimal point • An integer can be either positive or negative • Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
  • 35. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) • In the following example $x is an integer. The PHP var_dump() function returns the data type and value: <?php $x = 5985; var_dump($x); ?> PHP Float • A float (floating point number) is a number with a decimal point or a number in exponential form. e.g. $x = 10.365;
  • 36. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Boolean • A Boolean represents two possible states: TRUE or FALSE. • Booleans are often used in conditional testing. $x = true; $y = false; PHP Array • An array stores multiple values in one single variable. • In the following example $cars is an array. $cars = array("Volvo","BMW","Toyota");
  • 37. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Object • An object is a data type which stores data and information on how to process that data. • In PHP, an object must be explicitly declared. • First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods: <?php class Car { function Car() { $this->model = "VW"; } } // create an object $herbie = new Car(); // show object properties echo $herbie->model; ?>
  • 38. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP NULL Value • Null is a special data type which can have only one value: NULL. • A variable of data type NULL is a variable that has no value assigned to it. Tip: If a variable is created without a value, it is automatically assigned a value of NULL. Variables can also be emptied by setting the value to NULL: <?php $x = "Hello world!"; $x = null; var_dump($x); ?>
  • 39. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Variables in PHP • Variables are "containers" for storing information. Creating (Declaring) PHP Variables • In PHP, a variable starts with the $ sign, followed by the name of the variable: • <?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?>
  • 40. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Variables • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). • Rules for PHP variables: 1. A variable starts with the $ sign, followed by the name of the variable 2. A variable name must start with a letter or the underscore character 3. A variable name cannot start with a number 4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive ($age and $AGE are two different variables)
  • 41. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Output Variables • The PHP echo statement is often used to output data to the screen. • The following example will show how to output text and a variable: • Example <?php $txt = "W3Schools.com"; echo "I love $txt!"; ?>
  • 42. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Variables Scope • In PHP, variables can be declared anywhere in the script. • The scope of a variable is the part of the script where the variable can be referenced/used. • PHP has three different variable scopes:  Local  Global  Static
  • 43. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Global and Local Scope • A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: Example Variable with global scope: <?php $x = 5; // global scope function myTest() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?>
  • 44. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Variable with local scope: <?php function myTest() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } myTest(); // using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>"; ?>
  • 45. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP The static Keyword • Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. • To do this, use the static keyword when you first declare the variable: • Example <?php function myTest() { static $x = 0; echo $x; $x++; } myTest(); myTest(); myTest(); ?>
  • 46. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Constants in PHP • Constants are like variables except that once they are defined they cannot be changed or undefined. • A constant is an identifier (name) for a simple value. The value cannot be changed during the script. • A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.
  • 47. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Create a PHP Constant • To create a constant, use the define() function. • Syntax define(name, value, case-insensitive) Parameters: name: Specifies the name of the constant value: Specifies the value of the constant case-insensitive: Specifies whether the constant name should be case- insensitive. Default is false Example Create a constant with a case-insensitive name: <?php define("GREETING", "Welcome to W3Schools.com!", true); echo greeting; ?>
  • 48. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Operators and Expressions PHP Operators • Operators are used to perform operations on variables and values. • PHP divides the operators in the following groups: 1. Arithmetic operators 2. Assignment operators 3. Comparison operators 4. Increment/Decrement operators 5. Logical operators 6. String operators 7. Array operators 8. Conditional assignment operators
  • 49. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Operator Name Example Result + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y ** Exponentiation $x ** $y Result of raising $x to the $y'th power PHP Arithmetic operators
  • 50. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Assignment Operators Assignment Same as... Description x = y x = y The left operand gets set to the value of the expression on the right 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
  • 51. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Comparison Operators Operator Name Example Result == Equal $x == $y Returns true if $x is equal to $y === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type != Not equal $x != $y Returns true if $x is not equal to $y <> Not equal $x <> $y Returns true if $x is not equal to $y !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y <=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.
  • 52. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Operator Name Description ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one PHP Increment / Decrement Operators • The PHP increment operators are used to increment a variable's value. • The PHP decrement operators are used to decrement a variable's value.
  • 53. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Logical Operators Operator Name Example Result and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true
  • 54. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP String Operators Operator Name Example Result . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
  • 55. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Array Operators Operator Name Example Result + Union $x + $y Union of $x and $y == Equality $x == $y Returns true if $x and $y have the same key/value pairs === Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types != Inequality $x != $y Returns true if $x is not equal to $y <> Inequality $x <> $y Returns true if $x is not equal to $y !== Non-identity $x !== $y Returns true if $x is not identical to $y
  • 56. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Conditional Assignment Operators Operator Name Example Result ?: Ternary $x = expr1 ? e xpr2 : expr 3 Returns the value of $x. The value of $x is expr2 if expr1 = TRUE. The value of $x is expr3 if expr1 = FALSE ?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x. The value of $x is expr1 if expr1 exists, and is not NULL. If expr1 does not exist, or is NULL, the value of $x is expr2. Introduced in PHP 7
  • 57. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) printing data on PHP page • The PHP print Statement • The print statement can be used with or without parentheses: print or print(). Display Text The following example shows how to output text with the print command (notice that the text can contain HTML markup): Example <?php print "<h2>PHP is Fun!</h2>"; print "Hello world!<br>"; print "I'm about to learn PHP!"; ?>
  • 58. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Control Statements- if, switch case, for, while, do while • If The if construct allows you to execute a piece of code if the expression provided along with it evaluates to true. <?php $age = 50; if ($age > 30) { echo "Your age is greater than 30!"; } ?>
  • 59. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) • Else In the previous section, we discussed the if construct, which allows you to execute a piece of code if the expression evaluates to true. On the other hand, if the expression evaluates to false, it won't do anything. More often than not, you also want to execute a different code snippet if the expression evaluates to false. That's where the else statement comes into the picture. if (expression) { // code is executed if the expression evaluates to TRUE } else { // code is executed if the expression evaluates to FALSE }
  • 60. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Switch The switch statement is somewhat similar to the elseif statement which we've just discussed in the previous section. The only difference is the expression which is being checked. In the case of the elseif statement, you have a set of different conditions, and an appropriate action will be executed based on a condition. On the other hand, if you want to compare a variable with different values, you can use the switch statement.
  • 61. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) <?php $favourite_site = 'Code'; switch ($favourite_site) { case 'Business': echo "My favourite site is business.tutsplus.com!"; break; case 'Code': echo "My favourite site is code.tutsplus.com!"; break; case 'Web Design': echo "My favourite site is webdesign.tutsplus.com!"; break; case 'Music': echo "My favourite site is music.tutsplus.com!"; break; case 'Photography': echo "My favourite site is photography.tutsplus.com!"; break; default: echo "I like everything at tutsplus.com!"; } ?>
  • 62. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) While Loop The while loop is used when you want to execute a piece of code repeatedly until the while condition evaluates to false. while (expression) { // code to execute as long as expression evaluates to TRUE } Do-While Loop The do-while loop is very similar to the while loop, with the only difference being that the while condition is checked at the end of the first iteration. Thus, we can guarantee that the loop code is executed at least once, irrespective of the result of the while expression. do { // code to execute } while (expression);
  • 63. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) For Loop Generally, the for loop is used to execute a piece of code for a specific number of times. In other words, if you already know the number of times you want to execute a block of code, it's the for loop which is the best choice. for (expr1; expr2; expr3) { // code to execute }
  • 64. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Initialization of an array PHP array() Function <?php $cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?> Iterating through an array PHP's fo reach loop provides a convenient way to iterate over arrays. There are two forms: one uses both the key and value of each array entry while the other uses only the value. First we demonstrate the key => value form: $pets = ['Morie', 'Miki', 'Halo', 'lab' => 'Winnie']; foreach ($pets as $key => $val) { echo "$key => $val n"; } /* echo output (page source view) 0 => Morie 1 => Miki 2 => Halo lab => Winnie */
  • 65. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Sorting arrays PHP - Sort Functions For Arrays • sort() - sort arrays in ascending order • rsort() - sort arrays in descending order • asort() - sort associative arrays in ascending order, according to the value • ksort() - sort associative arrays in ascending order, according to the key • arsort() - sort associative arrays in descending order, according to the value • krsort() - sort associative arrays in descending order, according to the key Sort Array in Ascending Order - sort() <?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); ?>
  • 66. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) • Sort Array in Descending Order - rsort() <?php $cars = array("Volvo", "BMW", "Toyota"); rsort($cars); ?> • Sort Array (Ascending Order), According to Value - asort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); asort($age); ?> • Sort Array (Ascending Order), According to Key - ksort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); ksort($age); ?>
  • 67. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Sort Array (Descending Order), According to Value - arsort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); arsort($age); ?> Sort Array (Descending Order), According to Key - krsort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); krsort($age); ?>
  • 68. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Array Functions PHP Array Functions allow you to interact with and manipulate arrays in various ways. PHP arrays are essential for storing, managing, and operating on sets of variables. PHP supports simple and multi-dimensional arrays and may be either user created or created by another function. Installation There is no installation needed to use PHP array functions; they are part of the PHP core and comes alongwith standard PHP installation. Runtime Configuration This extension has no configuration directives defined in php.ini. PHP Array Functions Following table lists down all the functions related to PHP Array. Here column version indicates the earliest version of PHP that supports the function.
  • 69. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Sr.No Function & Description Version 1 array()Create an array 4.2.0 2 array_change_key_case()Returns an array with all keys in lowercase or uppercase 4.2.0 3 array_chunk()Splits an array into chunks of arrays 4.2.0 4 array_column()Return the values from a single column in the input array 5.5.0 5 array_combine()Creates an array by using one array for keys and another for its values 5
  • 70. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) 5 array_count_values()Returns an array with the number of occurrences for each value 4 6 array_diff()Compares array values, and returns the differences 4 7 array_diff_assoc()Compares array keys and values, and returns the differences 4 8 array_diff_key()Compares array keys, and returns the differences 5 9 array_diff_uassoc()Compares array keys and values, with an additional user- made function check, and returns the differences 5 10 array_diff_ukey()Compares array keys, with an additional user-made function check, and returns the differences 5
  • 71. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) 11 array_fill()Fills an array with values 4 12 array_fill_keys()Fill an array with values, specifying keys 5 13 array_filter()Filters elements of an array using a user-made function 4 14 array_flip()Exchanges all keys with their associated values in an array 4 15 array_intersect()Compares array values, and returns the matches 4 16 array_intersect_assoc()Compares array keys and values, and returns the matches 4
  • 72. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) 17 array_intersect_key()Compares array keys, and returns the matches 5 18 array_intersect_uassoc()Compares array keys and values, with an additional user-made function check, and returns the matches 5 19 array_intersect_ukey()Compares array keys, with an additional user- made function check, and returns the matches 5 20 array_key_exists()Checks if the specified key exists in the array 4 21 array_keys()Returns all the keys of an array 4 22 array_map()Sends each value of an array to a user-made function, which returns new values 4
  • 73. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Defining and Calling Functions PHP Functions PHP Built-in Functions • A function is a self-contained block of code that performs a specific task. • PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc. PHP User-Defined Functions • In addition to the built-in functions, PHP also allows you to define your own functions. • It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately form main program.
  • 74. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Creating and Invoking Functions • The basic syntax of creating a custom function can be give with: function functionName(){ // Code to be executed } • The declaration of a user-defined function start with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}. • This is a simple example of an user-defined function, that display today's date: <?php // Defining function function whatIsToday(){ echo "Today is " . date('l', mktime()); } // Calling function whatIsToday(); ?>
  • 75. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Passing by Value and passing by references Pass by Value: By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn’t have any effect on either of the variables. Example: <?php // Function used for assigning new // value to $string variable and // printing it function print_string( $string ) { $string = "Function geeksforgeeks"."n"; // Print $string variable print($string); } // Driver code $string = "Global geeksforgeeks"."n"; print_string($string); print($string); ?> Output: Function geeksforgeeks Global geeksforgeeks
  • 76. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference. Therefore, whenever global variable is change, variable inside function also gets changed and vice-versa is applicable. Example: <?php // Function used for assigning new value to // $string variable and printing it function print_string( &$string ) { $string = "Function geeksforgeeks n"; // Print $string variable print( $string ); } // Driver code $string = "Global geeksforgeeks n"; print_string( $string ); print( $string ); ?> Output: Function geeksforgeeks Function geeksforgeeks
  • 77. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Built in Functions These built in functions are what make PHP a very efficient and productive scripting language. The built in functions can be classified into many categories. Below is the list of the categories. String Functions • These are functions that manipulate string data, refer to the article on strings for implementation examples of string functions 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. Date Function • The date function is used to format Unix date and time to human readable format. • Other functions These include; • Arrays – see the article on arrays for examples • Files – see the article on files for examples • Database functions – see the article on MySQL PHP and other database access methods v2
  • 78. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) BCA Semester: FIFTH Semester Name of the Subject: WEB BASED PROGRAMMING (PHP) Unit-3 FACULTY NAME: Ms.Rekha Jain
  • 79. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) UNIT-2 Working with Forms Get and Post Methods There are two ways the browser client can send information to the web server. • The GET Method • The POST Method Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand. name1=value1&name2=value2&name3=value3 Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
  • 80. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) The GET Method The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. http://www.test.com/index.htm?name1=value1&name2=value2 • The GET method produces a long string that appears in your server logs, in the browser's Location: box. • The GET method is restricted to send upto 1024 characters only. • Never use GET method if you have password or other sensitive information to be sent to the server. • GET can't be used to send binary data, like images or word documents, to the server. • The data sent by GET method can be accessed using QUERY_STRING environment variable. • The PHP provides $_GET associative array to access all the sent information using GET method.
  • 81. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) The POST Method The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. • The POST method does not have any restriction on data size to be sent. • The POST method can be used to send ASCII as well as binary data. • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure. • The PHP provides $_POST associative array to access all the sent information using POST method. The $_REQUEST variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
  • 82. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Query string • The information can be sent across the web pages. This information is called query string. • This query string can be passed from one page to another by appending it to the address of the page. • You can pass more than one query string by inserting the & sign between the query strings. • A query string can contain two things:  the query string ID  and its value. • The query string passed across the web pages is stored in $_REQUEST, $_GET, or $_POST variable. • Whether you passed the query string by using GET or POST method, it is stored in $_REQUEST variable. • You should note that whether the query string is passed by the GET or POST method it can be accessed by using the $_REQUEST variable.
  • 83. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) HTML form controls and PHP PHP - A Simple HTML Form The example below displays a simple HTML form with two input fields and a submit button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
  • 84. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method. To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this: <html> <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html> The output could be something like this: Welcome John Your email address is john.doe@example.com
  • 85. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Maintaining User State HTTP is a stateless protocol which means every user request is processed independently and it has nothing to do with the requests processed before it. Hence there is no way to store or send any user specific details using HTTP protocol. But in modern applications, user accounts are created and user specific information is shown to different users, for which we need to have knowledge about who the user(or what he/she wants to see etc) is on every webpage. PHP provides for two different techniques for state management of your web application, they are: • Server Side State Management • Client Side Server Management Client Side State Management In client side state management the user specific information is stored at the client side i.e. in the bowser. Again, this information is available on all the webpages of the web application.
  • 86. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Cookies • Cookie is a small piece of information stored as a file in the user's browser by the web server. Once created, cookie is sent to the web server as header information with every HTTP request. • You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size. Realworld Use of Cookies  To store user information like when he/she visited, what pages were visited on the website etc, so that next time the user visits your website you can provide a better user experience.  To store basic website specific information to know this is not the first visit of user.  You can use cookies to store number of visits or view counter.
  • 87. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Types of Cookies There are two types of cookies, they are: • Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the browser is closed. • Persistent Cookie: To make a cookie persistent we must provide it with an expiration time. Then the cookie will only expire after the given expiration time, until then it will be a valid cookie. Creating a Cookie in PHP • In PHP we can create/set a cookie using the setcookie() function. Syntax: setcookie(name, value, expire, path, domain, secure)
  • 88. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Argument What is it for? name Used to specify the name of the cookie. It is a mandatory argument. Name of the cookie must be a string. value Used to store any value in the cookie. It is generally saved as a pair with name. For example, name is userid and value is 7007, the userid for any user. expire Used to set the expiration time for a cookie. if you do not provide any value, the cookie will be treated as a session cookie and will expire when the browser is closed. path Used to set a web URL in the cookie. If set, the cookie will be accessible only from that URL. To make a cookie accessible through a domain, set '/' as cookie path. domain The domain of your web application. It can be used to limit access of cookie for sub- domains. For example, if you set the domain value as wwww.studytonight.com, then the cookie will be inaccessible from blog.studytonight.com secure If you set this to 1, then the cookie will be available and sent only over HTTPS connection.
  • 89. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) So if we want to create a cookie to store the name of the user who visited your website, and set an expiration time of a week, then we can do it like this, <?php setcookie("username", "iamabhishek", time()+60*60*24*7); ?> Updating Cookie in PHP To update/modify a cookie, simply set it again. For example, if we want to update the username stored in the cookie created above, we can do it using setcookie() method again,
  • 90. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) <?php // updating the cookie setcookie("username", "iamNOTabhishek", time()+60*60*24*7); ?> <html> <body> <?php // check if the cookie exists if(isset($_COOKIE["username"])) { echo "Cookie set with value: ".$_COOKIE["username"]; } else { echo "cookie not set!"; } ?> </body> </html> We just update the value of username cookie from iamabhishek to iamNOTabhishek.
  • 91. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Delete a Cookie in PHP To delete/remove a cookie, we need to expire the cookie, which can be done by updating the cookie using the setcookie() function with expiration date in past. <?php // updating the cookie setcookie("username", "iamNOTabhishek", time() - 3600); ?> <html> <body> <?php echo "cookie username is deleted!"; ?> </body> </html>
  • 92. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Sessions • To store information accessible accross web pages, we use sessions. Session is not stored on the user browser like cookie, hence it is a more secure option. • When a user logs into their account on any web application, a session is created for them, and in the session their username or userid or some other unique identifier is stored, which is then used on the consecutive webpages to show information specific to that user. On logout, the session is destroyed. • Session is not limited by any size limit, you can store any information in the session, irrespective of its size. Realworld Use of Session • Web applications which require a user to login, use session to store user information, so that on every webpage related information can be displayed to the user. • In eCommerce websotes, shopping cart is geberally saved as part of session.
  • 93. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Start a Session in PHP • In PHP we can start a session by using the session_start() function. And data is stored in the session using session variable, which can be assigned different values using global variable $_SESSION • In simpler words, using the function session_start() we initialize the session, in which we can store information using the session variable $_SESSION. Let's take an example, below we have a webpage with Php file named first_page.php
  • 94. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) <?php // start the session session_start(); // set the session variable $_SESSION["username"] = "iamabhishek"; $_SESSION["userid"] = "1"; ?> <html> <body> <?php echo "Session variable is set."; ?> <a href="second_page.php">Go to Second Page</a> </body> </html> NOTE: The function session_start() should be the first statement of the page, before any HTML tag.
  • 95. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Getting PHP Session Variable Values In the code above, we have started a session and set two session variables. Above webpage will also have a link to navigate to Second page second_page.php. Below is the code for second_page.php, in which we fetch values from the session variable which are set in the first_page.php. <?php // start the session session_start(); // get the session variable values $username = $_SESSION["username"]; $userid = $_SESSION["userid"]; ?> <html> <body> <?php echo "Username is: ".$username."<br/>"; echo "User id is: ".$userid; ?> </body> </html>
  • 96. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Update Session Variable in PHP To update any value stored in the session variable, start the session by calling session_start() function and then simply overwrite the vakue to update session variable. <?php // start the session session_start(); // update the session variable values $_SESSION["userid"] = "1111"; ?> <html> <body> <?php echo "Username is: ".$username."<br/>"; echo "User id is: ".$userid; ?> </body> </html>
  • 97. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Destroy a Session in PHP To clean the session variable or to remove all the stored values from the session variable we can use the function session_unset() and to detroy the session, we use session_destroy() function. <?php // start the session session_start(); ?> <html> <body> <?php // clean the session variable session_unset(); // destroy the session session_destroy(); ?> </body> </html>
  • 98. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Working With Files Opening and Closing Files PHP Open File - fopen() A better method to open files is with the fopen() function. This function gives you more options than the readfile() function. The file may be opened in one of the following modes: Modes Description r Open a file for read only. File pointer starts at the beginning of the file w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x Creates a new file for write only. Returns FALSE and an error if file already exists r+ Open a file for read/write. File pointer starts at the beginning of the file w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
  • 99. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Read File - fread() The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read. The following PHP code reads the "webdictionary.txt" file to the end: fread($myfile,filesize("webdictionary.txt")); PHP Close File - fclose() The fclose() function is used to close an open file. The fclose() requires the name of the file (or a variable that holds the filename) we want to close: <?php $myfile = fopen("webdictionary.txt", "r"); // some code to be executed.... fclose($myfile); ?>
  • 100. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Read Single Line - fgets() The fgets() function is used to read a single line from a file. The example below outputs the first line of the "webdictionary.txt" file: <?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fgets($myfile); fclose($myfile); ?>
  • 101. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Reading and Writing to Files Reading a file • Once a file is opened using fopen() function it can be read with a function called fread(). • This function requires two arguments. • These must be the file pointer and the length of the file expressed in bytes. • The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes. • ]So here are the steps required to read a file with PHP.  Open a file using fopen() function.  Get the file's length using filesize() function.  Read the file's content using fread() function.  Close the file with fclose() function.
  • 102. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) The following example assigns the content of a text file to a variable then displays those contents on the web page. <html> <head> <title>Reading a file using PHP</title> </head> <body> <?php $filename = "tmp.txt"; $file = fopen( $filename, "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $filesize = filesize( $filename ); $filetext = fread( $file, $filesize ); fclose( $file ); echo ( "File size : $filesize bytes" ); echo ( "<pre>$filetext</pre>" ); ?> </body> </html>
  • 103. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Writing a file • A new file can be written or text can be appended to an existing file using the PHP fwrite() function. • This function requires two arguments specifying a file pointer and the string of data that is to be written. • Optionally a third integer argument can be included to specify the length of the data to write. • If the third argument is included, writing would will stop after the specified length has been reached. The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument
  • 104. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) <?php $filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple testn" ); fclose( $file ); ?> <html> <head> <title>Writing a file using PHP</title> </head> <body>
  • 105. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) <?php $filename = "newfile.txt"; $file = fopen( $filename, "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $filesize = filesize( $filename ); $filetext = fread( $file, $filesize ); fclose( $file ); echo ( "File size : $filesize bytes" ); echo ( "$filetext" ); echo("file name: $filename"); ?> </body> </html>
  • 106. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Getting Information on Files As a Web developer, it's common to have to interact with files on disk: check disk usage, read file permissions, find file modification times, and read file contents. Fortunately PHP comes with a full-fledged set of file functions for just this purpose and this document lists them all, together with usage examples (See Table A). Keep reading, you might discover something new! Function Explanation Example filesize($file) This function returns the size of a file, in bytes. It's useful to calculate how much space a file occupies on disk. <?php // get file size in bytes echo "Size is " . filesize('myfile.html') . " bytes"; ?> fileowner($file) filegroup($file) These functions return the owner and group ID for a file. They're useful to find out who "owns" a particular file. <?php // get file owner and group echo "UID: " . fileowner('myfile.html'); echo "GID: " . filegroup('myfile.html'); ?>
  • 107. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) fileatime($file) filemtime($file) These functions return a timestamp indicating when a file was last accessed and modified respectively. They're useful to find out if a file has changed since a particular date. <?php // get file access/modification times echo "Last accessed on: " . date("d-m-y", fileatime('myfile.html')); echo "Last modified on: " . date("d-m-y", filemtime('myfile.html')); ?> fileperms($file) This function returns the permissions of a file. Use it to check if a file is readable, writable or executable. <?php // get permissions in octal format echo "File permissions: " . sprintf('%o', fileperms('myfile.html')); ?> filetype($file) This function returns the "type" of a file - whether link, directory, character or block device, or regular file. Use this to test the nature of a file before using it in an operation. <?php // get file type echo "File type: " . filetype('myfile.html'); ?>
  • 108. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) stat($file) This function is a "catch all" function that returns detailed statistics about a file, including its owner and group, size, time of last change, block usage and inode number. Use this function instead of the functions listed previously if you need to obtain complete file statistics in a single call. <?php // get file statistics print_r(stat('myfile.html')); ?> realpath($f ile) This function turns a relative file path into an absolute path. It's useful when you need to find out exactly where a file is located on disk. <?php // get absolute path // returns "/tmp/myfile.html" echo "File path: " . realpath("./cook/book/../../myfile.html"); ?> basename( $file) dirname($ path) Given a complete file path, these functions can split it into its constituent parts and separately return the file name and directory name respectively. <?php // split directory and file names // returns "/usr/local/bin" echo "Directory: " . dirname("/usr/local/bin/php"); // returns "php" echo "File: " . basename("/usr/local/bin/php"); ?>
  • 109. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) file($file) This function reads the contents of a file into an array. Each element of the array represents one line of the file. This function is useful to read a file's contents into a variable, so that it can be processed further. <?php // read file contents $lines = file('myfile.html'); // print line by line for($x=1; $x<=sizeof($lines); $x++) { echo "Line $x: " . $lines[$x-1] . "n"; } ?>
  • 110. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) BCA Semester: FIFTH Semester Name of the Subject: WEB BASED PROGRAMMING (PHP) Unit-4 FACULTY NAME: Ms.Rekha Jain
  • 111. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) PHP Database connectivity Introduction to MYSQL What is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows. • MySQL is a database system that runs on a server. • MySQL is ideal for both small and large applications. • MySQL is very fast, reliable, and easy to use database system.It uses standard SQL • MySQL compiles on a number of platforms. How to connect PHP with MySQL Database? PHP 5 and later can work with a MySQL database using: • MySQLi extension. • PDO (PHP Data Objects).
  • 112. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Connecting to a database There are 3 ways in which we can connect to MySQl from PHP as listed above and described below: 1. Using MySQLi object-oriented procedure: We can use the MySQLi object-oriented procedure to establish a connection to MySQL database from a PHP script. Syntax: <?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating connection $conn = new mysqli($servername, $username, $password); // Checking connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?> OUTPUT: Connected successfully
  • 113. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) 2. Using MySQLi procedural procedure : There is also a procedural approach of MySQLi to establish a connection to MySQL database from a PHP script as described below. Syntax: <?php $servername = "localhost"; $username = "username"; $password = "password"; // Creating connection $conn = mysqli_connect($servername, $username, $password); // Checking connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfuly"; ?>
  • 114. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) 3. Using PDO procedure: PDO stands for PHP Data Objects. That is, in this method we connect to the database using data objects in PHP as described below: Syntax: <?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // setting the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
  • 115. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Closing A Connection When we establish a connection to MySQL database from a PHP script , we should also disconnect or close the connection when our work is finished. Here we have described the syntax of closing the connection to a MySQL database in all 3 methods described above. We have assumed that the reference to the connection is stored in $conn variable. • Using MySQLi object oriented procedure Syntax$conn->close(); • Using MySQLi procedural procedure Syntaxmysqli_close($conn); • Using PDO procedure Syntax$conn = null;
  • 116. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Use a particular database It is very simple to select a database from the mysql> prompt. You can use the SQL command use to select a database. Here is an example to select a database called TUTORIALS − [root@host]# mysql -u root -p Enter password:****** mysql> use TUTORIALS; Database changed mysql> Selecting a MySQL Database Using PHP Script PHP provides function mysql_select_db to select a database. It returns TRUE on success or FALSE on failure. Syntax bool mysql_select_db( db_name, connection );
  • 117. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Example Here is an example showing you how to select a database. <html> <head> <title>Selecting MySQL Database</title> </head> <body> <?php $dbhost = 'localhost:3036'; $dbuser = 'guest'; $dbpass = 'guest123'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_select_db( 'TUTORIALS' ); mysql_close($conn); ?> </body> </html>
  • 118. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Sending query to database PHP mysqli query() Function <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); // Check connection if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); } // Perform query if ($result = $mysqli -> query("SELECT * FROM Persons")) { echo "Returned rows are: " . $result -> num_rows; // Free result set $result -> free_result(); } $mysqli -> close(); ?>
  • 119. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Definition and Usage The query() / mysqli_query() function performs a query against a database. Syntax • Object oriented style: $mysqli -> query(query, resultmode) • Procedural style: mysqli_query(connection, query, resultmode) Parameter Description connection Required. Specifies the MySQL connection to use query Required. Specifies the SQL query string resultmode Optional. A constant. Can be one of the following: •MYSQLI_USE_RESULT (Use this to retrieve large amount of data) •MYSQLI_STORE_RESULT (This is defaul Parameter Values:
  • 120. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Parsing of the query results Query Processing includes translations on high level Queries into low level expressions that can be used at physical level of file system, query optimization and actual execution of query to get the actual result. Block Diagram of Query Processing is as:
  • 121. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Detailed Diagram is drawn as:
  • 122. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) It is done in the following steps: Step-1: Parser: During parse call, the database performs the following checks- Syntax check, Semantic check and Shared pool check, after converting the query into relational algebra.Parser performs the following checks as (refer detailed diagram): • Syntax check – concludes SQL syntactic validity. Example:SELECT * FORM employee Here error of wrong spelling of FROM is given by this check. • Semantic check – determines whether the statement is meaningful or not. Example: query contains a tablename which does not exist is checked by this check. • Shared Pool check – Every query possess a hash code during its execution. So, this check determines existence of written hash code in shared pool if code exists in shared pool then database will not take additional steps for optimization and execution.
  • 123. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Hard Parse and Soft Parse – If there is a fresh query and its hash code does not exist in shared pool then that query has to pass through from the additional steps known as hard parsing otherwise if hash code exists then query does not passes through additional steps. It just passes directly to execution engine (refer detailed diagram). This is known as soft parsing. Hard Parse includes following steps – Optimizer and Row source generation. Step-2: Optimizer: During optimization stage, database must perform a hard parse atleast for one unique DML statement and perform optimization during this parse. This database never optimizes DDL unless it includes a DML component such as subquery that require optimization.It is a process in which multiple query execution plan for satisfying a query are examined and most efficient query plan is satisfied for execution. Database catalog stores the execution plans and then optimizer passes the lowest cost plan for execution.
  • 124. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Row Source Generation – The Row Source Generation is a software that receives a optimal execution plan from the optimizer and produces an iterative execution plan that is usable by the rest of the database. the iterative plan is the binary program that when executes by the sql engine produces the result set. Step-3: Execution Engine: Finally runs the query and display the required result.
  • 125. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Checking data errors PHP mysqli error() Function Example - Object Oriented style Return the last error description for the most recent function call, if any: <?php $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); } // Perform a query, check for error if (!$mysqli -> query("INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Error description: " . $mysqli -> error); } $mysqli -> close(); ?>
  • 126. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Definition and Usage The error / mysqli_error() function returns the last error description for the most recent function call, if any. Syntax • Object oriented style: $mysqli -> error • Procedural style: mysqli_error(connection) Parameter Description connection Required. Specifies the MySQL connection to use Parameter Values
  • 127. Chanderprabhu Jain College of Higher Studies & School of Law Plot No. OCF, Sector A-8, Narela, New Delhi – 110040 (Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India) Example - Procedural Oriented style Return the last error description for the most recent function call, if any: <?php $con=mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } // Perform a query, check for error if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")) { echo("Error description: " . mysqli_error($con)); } mysqli_close($con); ?>