KEMBAR78
23ucas04 - PHP Notes | PDF | Websites | Dynamic Web Page
0% found this document useful (0 votes)
28 views101 pages

23ucas04 - PHP Notes

The document outlines a PHP Programming course offered at Arignar Anna College, detailing its curriculum across five units, which cover topics from basic PHP concepts to advanced functionalities like session management and file handling. It explains the differences between static and dynamic websites, including their creation methods, benefits, and drawbacks. The course aims to equip students with practical skills in web development using PHP and related technologies.

Uploaded by

mindcreativity6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views101 pages

23ucas04 - PHP Notes

The document outlines a PHP Programming course offered at Arignar Anna College, detailing its curriculum across five units, which cover topics from basic PHP concepts to advanced functionalities like session management and file handling. It explains the differences between static and dynamic websites, including their creation methods, benefits, and drawbacks. The course aims to equip students with practical skills in web development using PHP and related technologies.

Uploaded by

mindcreativity6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

ARIGNAR ANNA COLLEGE

(ARTS & SCIENCE)


KRISHNAGIRI

BACHELOR OF COMPUTER APPLICATIONS


21UCAS04 - SBE - PHP PROGRAMMING

M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

ASST.PROFESSOR

DEPARTMENT OF COMPUTer APPLICATIONS

ARIGNAR ANNA COLLEGE (ARTS & SCIENCE )

KRISHNAGIRI
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

SBE- PHP PROGRAMMING

UNIT - I
Introduction to PHP – Basic Knowledge of websites – Introduction of Dynamic
Website-Introduction to PHP-Scope of PHP-XAMPP and WAMP Installation.

UNIT – II
PHP Programming Basics -Syntax of PHP – Embedding PHP in HTML-Embedding
HTML in PHP. Introduction to PHP Variable -Understanding Data Types -Using Operators -
Using Conditional Statements -If( ), else if( ) and else if condition Statement.

UNIT – III
Switch( ) Statements-Using the while( ) Loop-Using the for( ) Loop - PHP Functions.
Creating an Array-Modifying Array Elements-Processing Arrays with Loops - Grouping
Form Selections with Arrays-Using Array Functions.

UNIT – IV
PHP Advanced Concepts -Reading and Writing Files -Reading Data from a File.

UNIT – V
Managing Sessions and Using Session Variables – Destroying a Session-Storing Data
in Cookies-Setting Cookies.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -1-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

UNIT - I
Introduction to PHP – Basic Knowledge of websites – Introduction of Dynamic
Website - Introduction to PHP - Scope of PHP-XAMPP and WAMP Installation.

BASIC KNOWLEDGE OF A WEBSITES:

What Is A Website?
➢ A website refers to a collection and conglomeration of inter-related web resources on
a given network.
➢ These resources can be classified as web pages or multimedia content and are
identified with the help of a common domain name.
➢ Usually, websites are dedicated to one particular topic or genre which can be anything
ranging from education to entertainment and business to health and hygiene.
➢ Websites are either identified with the help of a network of public Internet Protocol
(IP) such as the Internet or by employing a private local area network (LAN) through
a URL which identifies the site.
➢ Websites serve myriads of purposes and can be of varying types as well as natures.
➢ Let us discuss a bit about these aspects of a website.

Types Of Website
➢ Websites are of two types:
• Static
• Dynamic
➢ Both these websites are quite contrary to each other in terms of their nature and
purposes.

1. Static Website:
➢ As suggested by the name itself, these websites are static and fixed in nature. They
tend to display the exactly similar content for every single user which is mostly
written either in client-side HTML or in CSS codes.
➢ Static websites are purely informational in outlook are they usually appear with a
fixed number of pages having a specific layout. This particular rigidity in terms of the
structure of these sites is the prime reasons for their static nature.
➢ Since the mechanisms involved in a static website are relatively less complex than the
other types of websites, they are quite easy to create and time-efficient to use.
➢ Therefore, if you are willing to create a website which is supposed to display similar
content to all visitors, I’d suggest you create a static website.
2. Dynamic Website:
➢ Dynamic websites are those websites which aim to display different content to their
users.
➢ These sites are highly functional as they rely on both server-side and client-side
language scripts such as Java, ASP, or PHP.
➢ With the help of advanced databases and programming, these websites help the user
interact with the site on a significant scale.
➢ Dynamic websites require a lot of efforts as compared to the static website as they are
relatively more complex. However, they are immensely rewarding and popular among
users.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -2-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ After learning about the significance of various types of websites, you must be
thinking of creating one for yourself.
➢ But how to do that?
➢ It’s simple, just keep on scrolling down for learning about the most effective website
creation methods that are easy to use.

Website Creation Methods


➢ The two most potent methods to create an impactful website for your business are:

1. Programming
➢ If you are willing to create a static or interactive website for your niche, you can rely
upon the application of common programming languages for the purpose of website
creation.
➢ These programming languages are highly effective and quite easy to follow upon.
Some of the best languages available on the web are:

HyperText Markup Language


➢ HTML is one of the most prominent programming languages which is used to create
as well as design web sites and web pages.
➢ This programming language is popularly known as a markup language as it has the
availability of markup tags which are keywords having brackets around them.

Javascript
➢ This language is quite similar to other conventional computer programming
languages. Websites with Javascript allow its users to fulfil certain tasks on a website
in order to interact with the content.
➢ Its scripting language uses several functional calls in order to support the object-
oriented elements.
➢ JavaScript can be used in the form of PDF documents as well which is why it is
highly recommended.

PHP
➢ PHP is a server-side language in the form of a preprocessor hypertext, which basically
means that PHP enables every activity to be processed on the server and not on the
insides of the given browser.
➢ This server tends to process a web page prior than displaying it to the user which is
why it is highly admired.
➢ A PHP code can either be easily embedded inside a normal HTML document or can
be employed as a standalone file. However, in both cases, a server is required for
installation purposes.

Cascading Style Sheets (CSS)


➢ Cascading style sheets are a set of complementary programming languages which are
used to effectively style the HTML markup code.
➢ These languages are usually in consonance with each other but sometimes they can
act in isolation as well.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -3-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ This method of website styling proves to be incredibly beneficial for users as it allows
site developers to transform the similar HTML elements on a given page without the
requirement of changing it individually in isolation.
➢ Therefore, CSS offers the website developers the chance to save their valuable time as
well as allows them to test several design styles with a certain ease

Content Management System (CMS)


➢ CMS is a prolific software app which is popularly used for managing the creation as
well as the modification of the digital content of a given website.
➢ It is particularly used for web content management as well as for enterprise content
management. The best CMS one can use to develop a website is WordPress. It is by
far the most reliable CMS out there. Some other options when it comes to choosing a
CMS besides WordPress include SquareSpace, Wix, Blogger, OpenCart, and so on.
➢ All these website creation methods are highly effective and easy for users to apply.

What is a Dynamic Website?


➢ Dynamic Website is a website containing data that can be mutable or changeable. It
uses client-side or server scripting to generate mutable content. Like a static
website, it also contains HTML data.
➢ Dynamic websites are those websites that changes the content or layout with every
request to the webserver.
➢ These websites have the capability of producing different content for different
visitors from the same source code file.
➢ There are two kinds of dynamic web pages i.e. client side scripting and server side
scripting.
➢ The client-side web pages changes according to your activity on the web page.
➢ On the server-side, web pages are changed whenever a web page is loaded.
➢ Example: login & signup pages, application & submission forms, inquiry and
shopping cart pages.
A Typical Architecture of dynamic website

➢ There are different languages used to create dynamic web pages like PHP, ASP,
.NET and JSP.
➢ Whenever a dynamic page loads in browser, it requests the database to give
information depending upon user’s input.
➢ On receiving information from the database, the resulting web page is applied to the
user after applying the styling codes.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -4-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Why do you choose a dynamic page over a static page?


Why a company may require a dynamic page as compared to a static page, there are various
reasons, which are discussed below:
Need to access a database or external file
➢ A page needs to be dynamic, which needs to access an external file or a database to
get information.
➢ For case, whenever you visit Google and search any query, Google sends your search
for any query to multiple systems and combines all information into a search result
page.
Information is updated frequently
➢ When you update information on dynamic websites, they make it easier to update
information and faster to get information online.
➢ For instance, many different reporters can submit stories on a website.
➢ The company can update the home page automatically with the help of scripts to
have those stories.
➢ Also, the company does not need to depend on someone to modify a static HTML
page.
Dynamic sites make it easier for everyone to contribute
➢ Anyone who has much knowledge about programming or HTML also may make a
website with the help of WordPress sites and other CMS solutions.
➢ Once they have created a site, they can create pages with the help of using an online
editor as well a post them through th CMS. In contrast, with the static website, the
pages have to create in an HTML editor by the user and upload with the help of using
FTP.
Features of Dynamic Website
There are various features of a dynamic website, which are discussed below:
➢ Page Management: The software of page management or content management offers
users the tools that allow them to manage their websites as they want. For adding and
updating information on the site, they offer forms and templates that make it easy.
➢ Guestbook: A guestbook is a paper or electronic way for visitors, also known as a
visitor log, which is a way to acknowledge user visitation to place in the web-based
form or physical form. Generally, one leaves any comment, their postal address,
name, or note if required.
➢ Search Facility: This is the most important factor for a website because it helps to
explore your website. And, end-users will not be aware of the size of your Web site;
they will really want to use it. One of the widest tools is search engines used by end-
users.
➢ User Management: One of the most critical parts of maintaining a secure system is
user management, which describes how you can protect your server with the help of
using simple and effective user account management techniques.
➢ Contact Forms Management: It supports a wide range of contact form elements
allows you to create and manage different customized contact forms for your website.
Shortcodes are generated, which allow you to change contact form element properties,
and shortcodes do not need to replace every time.
➢ Header Banner Management: This allows extensive management of advertising
banner presentation as well as clickstream tracking. Through the URL (uniform
resource locator) of the GIF banner image file, banners can be stored on the remote
server, the exchange host server, or your server.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -5-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Multimedia File Management: You can upload new multimedia files on your
website by using Inigo's built-in multimedia manager, which you can use at any time
needed. You can also add custom filters that enable you to manipulate images
automatically to fit according to the site guidelines

Benefits of Dynamic Website


There are numerous benefits to choose a dynamic website design, which are given below:
Easy Updating
➢ One of the best benefits of choosing a dynamic website design is that it allows you to
update content easily based on your requirements.
➢ In changing the dynamic website, there is not a lot of computer knowledge is needed.
➢ In the template file, when you perform a single change, it will affect all the pages with
that specific file.
➢ While comparing with the static page, the dynamic page will be quickly updated to
become responsive for different screen sizes.
User Friendly
➢ The dynamic design of a website is very user-friendly, which allows users to make
changes to the website easily based on their requirements.
Interactive
➢ You can make a better user interface by using CSS (Cascading Style Sheet), which
makes the site more attractive.
➢ Also, on the sites, visitors can leave a reply or comment on the basis of their real-time
experience that helps the owner to know about the reviews of the customers through
which site owners can change their site accordingly.
➢ Furthermore, if users have any questions, they can ask on the site that would be
reverted by the website's owner.
➢ Therefore, a dynamic website is much ideal, even it is only possible with a dynamic
website.
Content Management System
➢ A dynamic website allows you to update information easily and quickly. For example,
you have a site that contains more than 50 pages, and you need to modify one menu
on your site.
➢ It can be changed by anyone who knows about the HTML coding for the same.
➢ If you do this every time, it may be difficult to do so. But with the dynamic website,
the website's owner can change only the portion of a particular section of the site
through CMS service.
Professional Look
➢ As compared to static websites, the looks of dynamic websites are more professional.
➢ Static Websites are usually ideal for showcasing your products on the website as well
as allows users to call and book orders; therefore, these websites often look
unprofessional. Hence, the looks of dynamic websites are more preferred.
Easily Manageable
➢ Dynamic sites can be built with an admin panel, and like PHP, MVC languages are
used by them to interact with information.
➢ These sites are built with an admin panel that makes it capable for the website's owner
to make changes in the website in a blink without the need for knowledge about any
programming language or coding.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -6-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Disadvantages of Dynamic website


Although dynamic websites have various benefits, they also have some difficulties; such are
as follows:
➢ One of the main limitations of the dynamic website is that it needs changes in a
certain period.
➢ Automation technology is required by developers that are not easy to get.
➢ To add to developers' budget for marketing, brand journalist or content marketing are
required to find or hire.
➢ These types of websites are complex.
➢ These are more expensive to develop.
➢ Hosting of these websites is also costlier.
➢ It requires a rapid, high-end web server.
➢ high production costs.
➢ Slow to load content.
➢ Client will require a skilled programmer to build a dynamic website.
➢ Hosting a website is costly as compared to a dynamic website.
➢ Low speed compared to a static website

Why should you choose a static page over a dynamic page?


There are some reasons why a company may need to choose a static page as compared to a
dynamic page or site, which are as follows:
Speed
➢ While comparing with the dynamic page generated server-side, a static HTML page
loads faster every time because it does not need an external resource.
➢ On the other hand, at least one request is needed for dynamic server-side sites that
increase the load time.
Portability
➢ Like a database, an external resource is not required by a static page, which allows the
page to work anywhere.
➢ For case, with the help of using a CDN, the page can be cached across multiple
servers and viewed offline.
Lower server requirements
➢ A static HTML page needs a lot of fewer system resources as it does not need any
server-side script or database to load the page.
➢ As compared to a server serving dynamic web pages, a static page serves more
visitors and performs a lot faster as it needs less from a server.

Application Of Dynamic Website:


Here is a list of application where we use dynamic website over static website
➢ Online booking system:
➢ E-commerce website.
➢ Voting or polls,
➢ Forums
➢ E-newsletter.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -7-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Real-life application:
Here is a list of application where we use dynamic website in real world.
➢ Facebook
➢ Twitter
➢ LinkedIn
➢ Online booking website.
➢ Social media
Introduction to PHP:
➢ Now let’s add PHP to the picture. PHP has several meanings depending on the
context in which it is used, so I’m going to try to explain them all.
➢ There is a “PHP server”, which is a web server that is running PHP software on it.
Let’s contrast a PHP server with a “plain” server, one that is not running PHP.
➢ A “plain” web server just takes a request from a browser, locates the appropriate file,
and sends it to the browser as is, with no manipulation. In other words, it only serves
static web pages.
➢ Once you add PHP to a web server, you get additional functionality—without taking
any existing functionality away.
➢ The server can still continue to send static HTML files to the browser, but it can also
manipulate the files prior to sending them to the browser.
➢ A file that has been manipulated prior to being sent to the browser is referred to as a
dynamic web page.
➢ A Static web page never changes , unless a person specifically edits the
page.
➢ A Dynamic web page can be different every time it is viewed by a
browser, because the server edits the page prior to sending it to the
browser , according to what instructions the programmer has coded into
that specific page.
Example :
➢ Here’s an example. Let’s say you have a web page on which you wanted the current
date to appear. With a static web page, you would have to go in and edit the page
every single day to update the date. That would get tiresome pretty quick!
The HTML code would look something like this:
<html>
<body>
Hello world! Today’s date is the 1st of September 2024
</body>
</html>
➢ With PHP you can let the server make the changes for you. In other words, PHP can
dynamically add the correct date to the page every time the page is served if you
insert a little bit of PHP code like this:
<html>
<body>
Hello world! Today’s date is <?php echo date(‘jS \o\f F Y’); ?>
</body>
</html>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -8-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Notice that the static text 1st of September 2024 has been replaced with <?php echo
date(‘jS \o\f F Y’); ?>.
➢ What we did was substitute the static text with code that will be converted into static
text by the server. (Sneak preview— PHP code appears in line with normal HTML
code and is identified by appearing within <?php and ?> tags).
➢ If you happened to open those two files using your browser on the 1st of September
2024, the two pages would be exactly the same.
➢ But on the 2nd of September 2024, the server takes the code above and turn it into
this:
<html>
<body>
Hello world! Today’s date is the 2st of September 2024
</body>
</html>
➢ And the cool thing is that it works every day, without any further manipulation.
➢ How does a server know whether a page should be dynamic or static? An ordinary
server only knows static pages.
➢ A PHP server knows that a file should be manipulated (it is dynamic) if it is “PHP
file” and that it should not be manipulated (it is static) if it is an HTML file.

What’s the difference between an HTML file and a PHP file?


➢ A PHP file is basically just an HTML file with some code inside it that tells the
server to swap out the code part and insert text (or HTML) in its place. A PHP file is
“just” an HTML file that has been saved with a different extension — “.php”. Here’s
an example:
➢ A PHP file is just an HTML file saved using a .php extension instead of an .html or
.htm extension , which tells the server to look in the page for code.
➢ What is the “extra code” that goes inside a PHP file instructing the page to be
manipulated? That’s PHP the language, which tells the server how and where the
page should be manipulated prior to sending it to the browser. In other words, PHP is
a programming language that is used to create dynamic web pages.
➢ PHP is a language that can be used to create dynamic web pages , In fact , that is the
point of PHP.
➢ How does the server know which parts of the page should be static and which parts
should be dynamic? In general, the server leaves the page alone. However, if it sees
the text <?php then all the text that follows will be treated like code, until it comes to
a ?> which signals the server to go back to sending the page as is.
➢ Text on a PHP page is normally static. The PHP server will dynamically convert the
text that appears in between <? php and ?> tags into static text, after evaluating what
the code means.

History Of PHP:
➢ PHP was first developed by Rasmus Lerdorf.
➢ He created a set of CGI script to monitor page views for his online resumes.
➢ The early version of PHP is PHP/FI. It supports for form Input and them SQL
database.
➢ It has lack of security features.
➢ Later it was improved and released has PHP/FI 2.0 in 1997.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -9-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Andi Gutmans and Zeev Suraski rewrote the PHP parser and released it as PHP 3.0.
➢ PHP 3.0’s syntax more powerful and consistent.
➢ PHP 4.0 was released in 2000. It offered a new engine, better performance and
reliability and built- in support for sessions and object oriented features.
➢ PHP 5.0 was released in 2004, was a radical redesign of PHP 4.0, a much improved
object model and various security performance improvements.
➢ PHP 5.0 also introduced various new and important tools:
➢ A common database access layer
➢ Java-style exception handling and
➢ An integrated database engine
➢ PHP 5.3 is the most recent version was released in January 2008.
➢ It improves the versions of PHP 5.0
✓ It supports:
✓ Name space
✓ Built in support for SQLite 3
✓ New native driver for MySQL
➢ PHP 5.3 is the best PHP released in the language’s fourteen year history, a fact amply
illustrated by the April 2008 Net craft survey, which shows PHP in use on over thirty
million web sites.
➢ PHP is now produced by The PHP Group and serves as the formal reference to the
PHP language. PHP is free software released under the PHP License, which is
incompatible with the GNU General Public License (GPL) due to restrictions on the
usage of the term PHP.
➢ While PHP originally stood for Personal Home Page, it is now said to stand for PHP:
Hypertext Preprocessor, a recursive acronym.

SCOPE OF PHP:

➢ PHP is the most required skill in current web development industry, the people who
want to design their own website using PHP language should learn PHP certification.
➢ PHP is a scripting language that has been wholeheartedly welcomed right from the
time it was introduced.
➢ Regardless of size, start-ups, small and big companies are looking forward to using
the immensely popular PHP web development.
➢ But there is a widespread doubt about the scope of PHP.
➢ The actual fact is that, without any doubt, PHP has a lot of scope now and forever.
➢ This is something studied and reported by many top PHP Training Institutes in
Companies prefer PHP as it creates more efficient and dynamic web solutions.
➢ A website is an ultimate doorway for any organization that is in the IT sector.
➢ This is why there is high demand for PHP developers.
➢ It is a simple yet powerful tool to start a website for any individual or company
purpose.
➢ PHP web development program is an open source scripting language that is fast and
is widely used to develop the wide variety of web and internet applications. It is
known for creating websites with much lesser efforts.
➢ It can also be embedded into HTML, which is another big benefit of PHP.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -10-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Most of the companies in recent times have been using the PHP language for
themselves.
➢ Many top IT companies in India and abroad are hiring many Indians as PHP
developers.
➢ These developers provide the best web solutions and designs on a global standard.
Companies look for high-quality certifications while hiring PHP developers.
➢ It is beneficial for those who are interested in pursuing a career in the IT sector.
➢ If you have proper training and certification, you will have a lot of opportunities both
in India as well as in abroad.
➢ The value for PHP Training certification is really high in many top companies.
➢ To attain proper training from the experts from the industry and become a certified
PHP developer, Join FITA.

Installing and Configuring PHP


Introduction
➢ Before you can begin using PHP, you need to have a copy of it. For the purposes ,
we’re going to install PHP on your local computer so you can play around with it
without too much fuss.
➢ Note that applications you write on your local computer can only be used on your
local computer, or by other computers on your local network.
➢ For the rest of this book, we are going to need Apache, MySQL, and PHP. Together,
this collection is referred to as AMP.
➢ When you run this on Linux, it’s called LAMP, and when you run it on Windows, it’s
called WAMP.
➢ Some people call this combination a “stack”, and may refer to the combination as the
“LAMP Stack”.
➢ Fortunately, this is a very popular combination and you don’t have to figure it all out
on your own.

WAMP

➢ WAMP is an acronym for Windows, Apache, MySQL, and PHP, it’s used as a Web
development platform that insists the users manage web apps using PHP, MySQL,
and Apache.
➢ It is free and an open-source web server solution stack package. It uses virtual hosts
and provides top services.

NOTE: WAMP IS DESIGNED ONLY FOR WINDOWS, IT CAN NOT BE


INSTALLED ON MAC OS AND LINUX

XAMPP

➢ XAMPP is an acronym for (X) cross-platform (Windows, Linux, Mac OS),


(A)Apache, (M)Maria DB or MySQL, (P)PHP and Perl. Like WAMP, XAMPP is
also a free and open-source platform used for web development.

NOTE: UNLIKE WAMP, XAMPP IS DESIGNED FOR WINDOWS, MAC OS AND


LINUX. SO IT CAN BE INSTALLED IN ALL OPERATING SYSTEMS
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -11-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Installation procedure
WAMP Server:
➢ Step 1
Use the official link to download the WAMP server. The web server has two versions:32-
bit and 64-bit. Download the version according to your system configurations.

➢ Step 2
Once you click the download option, you will receive some warnings. Just leave it and
click the link “download directly”

➢ Step 3
Now the “Select Setup Language box” will appear. Here you have to choose your
preferred language. You can choose your preferred language from the option and then
click “OK”

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -12-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Step 4
“The License Agreement” Window will appear. Tick the check box“I accept the
agreement” and click “Next”

➢ Step 5
Now a window displays the basic components that need to be in your computer, for the
proper functioning of the WAMP Server. Read the information and click “Next”

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -13-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Step 6
The “Select Destination Location” window appears. Select a location and click “Next”.

➢ Step 7
Now you have to select “Where to Set up program’s shortcuts?” Browse and select the
location. Click “Next”

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -14-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Step 8
The “Install window” appears, click “Install” and wait until the installation is complete.

➢ Step 9
Then, click “Next” on the information screen.

Click “Finish” to complete the installation.

That’s it. The WAMP is now located in the selected location that you have selected.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -15-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

WAMP for Mac


➢ You can not install WAMP on Mac (WAMP server on MacOs), as it was designed
only for Windows. There is no option to download WAMP for Mac.
WAMP for Linux
➢ You can not have Wamp on Linux also. WAMP is only for Windows OS. You can
use XAMPP for cross-platforms.
Note:
➢ LINUX and Mac OS users can’t use WAMP. Then no worries, we
have XAMPP which is exclusively designed for LINUX and Mac Os. Like WAMP,
installing XAMPP is also quite simple.
➢ Now let us learn about how to install XAMPP.
XAMPP Server:
➢ (Note: Follow the Xampp server installation steps with caution for the successful
installation of XAMPP.)
XAMPP for Windows:
➢ Step 1
Download the XAMPP file from the official
website https://www.apachefriends.org/index.html. You can choose Windows, Mac OS,
or Linux depending on your system.

➢ Step 2
The “User Account Control Window” will open. Click “Yes”. Now a warning appears, if
you have “User Account Control on your computer”, click “OK” on the warning.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -16-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Step 3
Click “Next” in the “Setup XAMPP Wizard page”.

➢ Step 4
Now, in the “setup xampp wizard” page select the components which you want to install.
And leave the others as unselected. You can find some components in gray color. These
are the components that are mandatory to run the software. And it will install
automatically. Then Click the icon “Next”.

➢ Step 5
In the installation folder page choose the destination, where you want to install. Click
“Next”(NOTE: If you activate UAC on your computer, then don’t install your XAMPP
on the hard drive like Local Disk C. Create a new folder to install XAMPP).

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -17-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

✓ If you activate UAC in your computer, then don’t install your XAMPP on the hard
drive like Local Disk C
✓ Click the folder-shaped icon select the “Make new folder” icon at the left bottom of
the page select the folder where the XAMPP is to be installed and click “OK” to
confirm the destination location.
✓ After selecting the destination folder click “Next”

➢ Step 6
✓ In the next window, If you want to learn about Bitnami, select the checkbox “
Learn more about Bitnami”.Otherwise, unselect the checkbox.
✓ Bitnami is used to install open-source applications like WordPress, Joomla,
Drupal, and many more on the installed XAMPP. Then click the “Next” icon.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -18-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Step 7
The “Ready to install” window opens. Click “Next” and install XAMPP.

➢ Step 8
After installing you will find “Completing the XAMPP setup Wizard”. On that wizard,
Select the check box ”Do you want to start the Control Panel now?”, Then Click “Finish”

➢ Step 9
In the language window select your preferred language and click “Next”.

(NOTE: If all the above steps are performed correctly, then the XAMPP control panel
opens smoothly.)

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -19-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Step 10
Click the Start button on Apache and MySQL. When you start the modules, you can see
the PID(Process ID) number and the port number that every module uses and their status
turns green.

Now the XAMPP is successfully installed in Windows.

WP Ultimate CSV Importer Pro


Get Ultimate CSV/XML Importer to import data on WordPress faster, quicker and
safer.

XAMPP for Mac


Follow the below steps to install XAMPP on Mac OS.
➢ Download the latest version of XAMPP on your Mac by clicking on this link Once
the dmg files are downloaded, you need to mount them on the Volumes directory by
entering the following command on the terminal.
➢ $ hdiutil mount Downloads/xampp-osx-8.2.4-0-installer.dmg
➢ With this command, an application file has been created on the /Volumes/XAMPP.
Open this file using the command $ open /Volumes/XAMPP/XAMPP.app
➢ The XAMPP setup wizard will be open. Click on the Next Button.
➢ Select all the components that you want to install and click Next.
➢ The location where the Xampp file will be installed was displayed on the screen.
Click Next.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -20-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ The Xampp installer is ready to install XAMPP, click on Next.


➢ Now the setup begins to install Xampp on your computer. Click Next.
➢ The Xampp starts downloading. Click on Finish, when the installation is completed.
➢ Now the Xampp has been installed in your Mac server.

Unmount the installer


➢ If you want to unmount the installer, enter the below command on the terminal.
➢ $ hdiutil unmount /Volumes/XAMPP

Xampp for Linux


➢ Download the Xampp for Linux from the official website.
➢ Make sure the XAMPP files have been downloaded to your Downloads folder.
➢ Once you have downloaded it, open the terminal by clicking on Alt + Ctrl + T.
➢ Then change over the downloaded files in the directory by entering the command cd
Downloads on the terminal.
➢ Then type the below command to make your downloaded file executable.
➢ chmod +x xampp-linux-x64-8.2.4-0-installer.run
➢ Here 8.2.4-0 is the version number of the Xampp file. Make sure you have entered the
version number of your Xampp. Then click on Enter.
➢ Now enter the installation command
➢ Click on Enter. Now it asks for the password of your computer and click on Enter.
Now the installation Window will appear.
➢ Follow the onscreen instructions by clicking on Next.
➢ On completing the Xampp Setup wizard make sure you have unchecked the Launch
Xampp checkbox.
➢ Now click on Finish.
➢ Your Xampp is now ready to work on your Linux OS.
➢ How to run Xampp on Linux:
➢ To run Xampp on Linux, first, reopen the terminal by clicking on the Alt+Ctrl+ T
➢ Xampp doesn’t have desktop files so, it is important to open the terminal and switch
to the directory by entering the command cd /opt/lampp
➢ Run the Xampp by entering sudo ./manager-linux-x64.run
➢ Click on Enter. Then type the password of your computer and click on Enter
➢ The Xampp window will be displayed. Navigate to the Manage Servers at the top bar
and click on Select All.
➢ This will run all the active components of Xampp. Once you run the Xampp, it will
show the IP address like 127.0.0.1
➢ Finally, navigate to the web browser and go to the localhost page of your computer by
entering 127.0.0.1 on your search console.
➢ At this point, you should see the Xampp dashboard to begin using the Xampp.
➢ You can test your web application and programs with these local host servers.
Without this XAMPP or WAMP, CRMs like Vtiger CRM, and SuiteCRM can’t be
installed in the localhost environment.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -21-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

XAMPP ERROR FIXING:


Why is XAMPP not installed? How to fix errors in XAMPP?
➢ XAMPP might not be installed due to various reasons such as incompatible system
requirements, anti-virus interference, or corrupted installation files. To fix errors, try
running the installer as an administrator, disabling the antivirus temporarily during
installation, or downloading a fresh copy of XAMPP from the official website.
➢ The first thing before troubleshooting is to identify the errors causing the disruption.
➢ While running Xampp, the below half of the control panel will display the error that
disrupts Xampp from running. Also, you can view the error log by clicking on the
logs from the right corner of Apache and MySQL. And selecting the error.log.

➢ The error log will list all the errors that stop Apache from working. You can easily
verify the error log and identify the errors.
➢ You can test the error log of MySQL by navigating to the Logs tab corresponding to
MySQL and selecting MySQL. Error.log.

TROUBLESHOOTING PORT CONFLICT ERROR


➢ This error will happen when Apache doesn’t run. It shows an error message that this
port is already in use.
➢ The Apache will always connect over port 80 by default. To view the available port
and the applications run on the port.
➢ Navigate to the Xampp Control Panel and click on the Netstat button. It will list all
the ports and the applications using them.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -22-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ You can easily remove the application that is disrupting the Xampp function and
unblock the desired port. Or you can change the listening port of your Apache to
8080.
➢ To change the Xampp Apache port,
• Navigate to the Xampp Control Panel->Click on the config button corresponding to
the Apache module.
• Select Apache(httpd.conf) file

• In this file, search the line that has Listen 80 and replace it with Listen 8080.
• Also, search for the line ServerName localhost:80 and replace it with ServerName
localhost:8080.
• Finally, Save the file.
➢ Now start running the Apache in Xampp’s Control Panel. It will run as intended. If
your WordPress site is hosted via Xampp, then you need to replace all the localhost
with localhost:8080 to run your Apache perfectly.
➢ Note that you need to enter http://localhost: 8080 rather than simply typing
http://localhost in your browser for the proper functioning of Xampp.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -23-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ If you have a port conflict error at Mac OS,


• Navigate to the Application and select Xampp in the Finder.
• Here you can find your Apache(httpd.conf) file.
• Follow the same steps described above to change the port in Windows.

INSTALLATION ERROR
To check if XAMPP is installed, look for its installation directory (usually in C:\xampp on
Windows or /opt/lampp on Linux), or try launching the XAMPP Control Panel application.
• Navigate to the Xampp location where it is installed
• Select the Xampp Control Panel from the list of options.
• It shows all the supported modules of Xampp. It includes Apache, MySQL, FileZilla,
Mercury, and Tomcat.
• Start the Apache and MySQL in the control panel.
• Open any browser and enter https://localhost. It will land you on the Xampp Screen.
• If it runs properly without an error, your Xampp has been installed properly.
➢ Next, we need to check whether the Xampp has been properly configured. So we need
to create a test file in the C:/Xampp/htdocs.
➢ Open the Notepad, write the below code, and save the file with the php extension.
<!doctype html>
<html>
<head>
<title> Test Page</title>
</head>
<body>
<p> XAMPP Server runs successfully</p>
</body>
</html>
➢ I have saved it as Xamp test.php.

➢ Now open any browser and enter localhost/Test/Xamp test


➢ If your screen displays Xampp server runs successfully, then your Xampp has been
properly configured.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -24-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Do I need to install PHP if I install XAMPP?


➢ No, XAMPP includes PHP along with other components like Apache, MySQL, and
Perl, providing a bundled solution for web development.
How do you install XAMPP when MySQL is already installed?
➢ If MySQL is already installed, it runs on port 3306 by default. You can run XAMPP
in a different port to avoid conflicts.
➢ While installing XAMPP ensure that the previously installed MySQL service is
stopped or not running during XAMPP installation.
➢ For that, navigate to the Windows search bar and search for the services
➢ Click on the services tab. You can easily stop MySQL from running by left-clicking
on the MySql services running status, and stop the service. Then, left-click on the
startup type and select Properties. Change the startup type from manual to automatic.
➢ Now you can easily run MySQL with XAMPP.
How do you install and configure the XAMPP server?
➢ To install XAMPP, download the installer from the official website and follow the on-
screen instructions.
➢ Configuration can be done through the XAMPP Control Panel, where you can start
and stop Apache, MySQL, and other services, and configure their settings.
➢ Refer to the above topics in this blog to get started with the step-by-step instructions
to install and configure the XAMPP server.
How to fix MySQL errors? Why is XAMPP MySQL not running?
➢ MySQL errors in XAMPP can be due to various reasons such as port conflicts,
incorrect configuration, or corrupted files.
➢ To fix MySQL errors, ensure that no other application is using the MySQL port,
check the MySQL configuration files for errors, and try restarting the MySQL service
from the XAMPP Control Panel.

OTHER ERRORS
Solutions to the error- MySQL stops unexpectedly
There are various reasons for the error MySQL stops unexpectedly. Below are some methods
to overcome this error and for the smooth functioning of the XAMPP server.
1. Troubleshooting MySQL port conflict error
➢ As we know, MySQL runs on port 3306. If any other applications use this port, then
on starting MySQL, it shows an error message MySQL stops unexpectedly.
➢ So, you can change the port to run MySQL. Before that, you need to know which
application uses which port.
➢ To know that, click on the Netstat button on the XAMPP Control Panel.
➢ It displays all the ports with which the applications are running. With this, you can get
the idea of unused ports to be assigned for MySQL.
➢ To change the port that conflicts,
➢ Open the XAMPP control panel
➢ Ensure that you have stopped all the running modules such as Apache and MySQL.
➢ Navigate the Config tab on the top right corner
➢ Click on the Port and settings
➢ Select the MySQL tab and change the Port number 3306 to some other unused port.
Preferably 3307 is used when Port 3306 runs some other applications

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -25-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Navigate to the Config tab corresponding to the MySQL button in XAMPP’s control panel.
Click on my.ini file

Replace all the word “Port=3306” to “Port=3307” throughout the file. Once done save the
file.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -26-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Now you can run your MySQL, which runs smoothly on your updated port 3307.
2. Run as Administrator
➢ If the error is not due to the port conflicts, then there may be any permission issues
that stop MySQL from running. You may run the XAMPP with Administrative
privileges and can solve the MySQL error.
➢ To run your XAMPP as administrator,
• Navigate to the file where the XAMPP Control Panel is located.
• Right-click on the file and select “Run as administrator”.
For Mac users,
• Right-click on the XAMPP control panel file.
• Navigate to the Get Info -> Sharing & Permissions Section -> Padlock icon
• Now enter your administrator password and change the Read & Write Permission
settings to Everyone.
• By running XAMPP with Administrative privileges you can easily access your
MySQL Databases and smoothly run MySQL in the XAMPP server.

Oracle VM Virtual Box


➢ If you are proficient with computers, you might like to try out a pre-configured virtual
machine.
➢ Oracle VirtualBox is free for you to use, and folders can be shared between the host
and guest machine allowing you to simply save the file you are working on and
refresh your browser, there’s no need to upload via FTP/SFTP to test your changes.
➢ If this sounds like a good option for you, here’s a link to a tutorial on setting it up.

Installing for a Web Site


➢ If you wanted to make your application available to everybody on the Internet, you’ll
need to install PHP and your application onto a publicly accessible server.
➢ This topic is covered in Appendix A: Installing PHP on a Website.
Exercise
➢ Use your editor (for instance, Programmers’ Notepad) to create a file containing the
following line:

➢ Save the file as phpinfo.php in the correct place on your hard drive (for instance,
C:\wamp\www).
➢ Finally, open the file with a browser by typing http://localhost/phpinfo.php
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -27-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

UNIT – II

PHP Programming Basics -Syntax of PHP – Embedding PHP in HTML-


Embedding HTML in PHP. Introduction to PHP Variable -Understanding Data Types -
Using Operators -Using Conditional Statements -If(), else if() and else if condition
Statement.
PHP PROGRAMMING BASICS:
Basic development concepts:
When developing a PHP application for the Web, the typical approach is to embed
PHP code into one or more standard HTML documents using special “tags,” or delimiters.
Here’s an example:
<html>
<head></head>
<body>
<div>
<?php echo sqrt(49); ?>
</div>
</body>
</html>
From the preceding explanation, it should be clear that to get started building PHP
applications, your
development environment must contain at least three components:
● A base operating system (OS) and server environment (usually Linux)
● A Web server (usually Apache on Linux or IIS on Windows) to intercept HTTP requests
and either
serve them directly or pass them on to the PHP interpreter for execution
● A PHP interpreter to parse and execute PHP code, and return the results to the Web server
There’s also
often a fourth optional but very useful component:
● A database engine (such as MySQL) that holds application data, accepts connections from
the PHP layer, and modifies or retrieves data from the database An important corollary of this
approach is that the PHP code is executed on the server, and not on the client browser. This
allows Web developers to write program code that is completely independent of, and thus
impervious to, browser quirks—an important advantage over client-side scripting languages,
such as JavaScript, which often require complex logic to account for browser-specific
differences. Further, because the code is all executed on the server and only the output is sent
to the client, it is impossible for users to see the source code of your PHP program—an
important security advantage over languages like JavaScript.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -28-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Basic PHP Syntax


➢ A PHP script always starts with <?php and ends with ?>. A PHP script can be placed
anywhere in the document.
<?php
// code
?>
➢ In PHP , we use // to make a one-line comment or /* and &/ to make a comment block
➢ A PHP file must have a .php extension. A PHP file normally contains HTML tags,
and some PHP scripting code. Before we go much further, it is important to note that
PHP is case sensitive. Be sure to follow the same casing you see in the examples.
Simple coding in PHP:
<html>
<head>
<body>
<?php echo ‘welcome to php’
?>
</body></head></html>
The development environment must contains at least three components:
1. A base operating system and server environment.
2. A web server usually apache on Linux or IIS on windows to intercept HTTP
requests and either serve them directly or pass them on the PHP interpreter for
execution.
3. A PHP interpreter to parse and execute PHP code, and return the results to the
web server.
4. Optional: The database engine such as MySQL that holds, application data
accept connections from the PHP layer, and modifies or retrieves data from the
database.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -29-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

CREATING YOUR FIRST PHP SCRIPT


Now that you know a little bit about PHP, let’s dive right in and begin writing some code. By
necessity, the scripts you’ll be writing in the following sections will be fairly simple but don’t
worry, things will get more complicated as you learn more about the language! If you haven’t
already done so, this is a good place to boot up your computer, download the newest versions
of Apache and PHP, and install them to your development environment. Appendix A of this
book has detailed instructions for accomplishing this procedure, and for testing your
development system to ensure that all is working as it should post-installation, so flip ahead
and come back here once you’re ready. All done? Let’s get started!
WRITING AND RUNNING THE SCRIPT
➢ PHP scripts are merely plain-text files containing PHP instructions, sometimes
combined with other odds and ends—JavaScript, HTML, and so on. So, the simplest
way to write a PHP script is to pop open your favorite text editor and create a file
containing some PHP code, as follows:
<?php
echo 'A horse! A horse! My kingdom for a horse!';
?>
➢ Save this file to a location under your Web server’s document root, and name it
horse.php. Then, start up your Web browser, and browse to the URL corresponding to
the file location.

UNDERSTANDING THE SCRIPT


➢ What happened here? Well, when you requested the script horse.php, the Apache
Web server received your request, recognized that the file was a PHP script (by means
of the .php file extension), and handed it off to the PHP parser and interpreter for
further processing.
➢ This PHP interpreter then read the instructions between the <?php ... ?> tags, executed
them, and passed the results back to the Web server, which in turn sent them back to
your browser.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -30-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ The instructions in this instance consisted of a call to PHP’s echo statement, which is
responsible for displaying output to the user; the output to be displayed is enclosed in
quotation marks.
➢ There is some useful information to be gleaned from even this simple PHP script. It
should be clear, for example, that all PHP code must be enclosed within <?php ... ?>
tags and every PHP statement must end in a semicolon.
➢ Blank lines within the PHP tags are ignored by the parser. Free-form comments can
be incorporated within a PHP script via the same conventions used in JavaScript.
➢ Single-line comments must be preceded by the // characters, while multiline
comments must be enclosed within a /* ... */ comment block. These comments are
excluded from the output of the PHP script. Here are some examples:
<?php
// a single-line comment
?>
<?php
/* a multi-line
comment
block */
?>

HANDLING SCRIPT ERRORS


➢ The PHP parser has a sharp eye. If your code includes an error, it will—depending on
the severity of the error—either display a warning message or stop script execution at
the point of error with a notification of what went wrong.
➢ Latter errors and error handling in detail, but it’s instructive at this point to see what
happens when the PHP parser encounters an error, so that you have a better
understanding of how to deal with this situation when it happens to you. To
deliberately generate an error, go back to the horse.php script you created earlier and
drop in an extra semicolon after the echo keyword, so that the script now looks like
this:
<?php
// this line of code displays a famous quotation
echo ; 'A horse! A horse! My kingdom for a horse!';
?>
➢ Save this file, and browse to it as before. This time, you should see something like the
PHP parser is quick to catch errors in your code. The error message generated by the
parser is quite helpful: it tells you what the error was, as well as the line on which it
occurred. This makes it fairly easy—in most cases—to locate and correct the error.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -31-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ When the PHP parser reads a script, it executes only the code found between PHP
tags; everything outside these tags is ignored by the parser and returned “as is.” This
makes it extremely easy to embed PHP code within an HTML document to create
Web pages that have all the formatting bells and whistles of standard HTML but can
additionally perform complex calculations or read and manipulate data from external
sources (such as databases or Web services).
Embedding PHP in HTML
➢ The following article provides an outline of Embed PHP in HTML.
➢ HTML is a pre-defined front end language code, whereas php is a server-side
scripting language; it is also called an embedded server-side language.
➢ Most of the PHP syntax codes has to be followed with the c, java and Perl script
languages.
➢ It normally works with other web-based dynamic script languages, and also
performance side, it will be more better compared to other script languages whereas it
is paired with html codes for creating web-based applications it is a non-interruptible
functioning type for creating the websites.
Syntax:
➢ The Embed PHP code is the standard one that is a normal html document; we have
written the PHP code on the html page.
Code:
<html>
<head>
<title>
</title>
<script language="php">
-----some codes----
</script>
</head>
</html>
➢ The above code is the basic syntax for embedding the php code in html page with the
help of <script> tags; it is also another type of style for portable codes.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -32-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

How to use Embed PHP in HTML?

➢ In Php code, we also wrote an embedded code inside. It normally looks like an
HTML code it also runs in the normal browsers as the source the raw PHP code is
not visible in the browsers because the interpreter in the PHP has run through the
script mode, and also it will display the output as from the expected script results
as the user is given inputs and getting outputs as test cases.
➢ This means that the PHP code, which we will already reproduce with the clean
html viewable codes with any type of web browsers, instead the user does not
understand the PHP codes in the browsers. This type of process will come in the
server-side scripting concepts in a nutshell thats why PHP has an interpreted and
executed within the web browsers compatible with any type of user’s local PCs.
➢ Generally, PHP codes have a basic type of syntax like html as the first type of
document. PHP tag will be used in the html code; in the below PHP tag, we will
write the logic using PHP syntax and statements and finally, it will have the
whitespace for comment purposes. The view part will be shown like normal html
codes because PHP codes are written in script tags.
Importance of Embed PHP in HTML

➢ PHP is also used as a command-line code script written in desktop applications or


standalone applications but mainly focuses on web-based applications. Normally the
client user sends the request to the server; the request itself has the PHP code is
happened, the response will be in either xml or json type it will become from the
server. PHP is used for creating dynamic web sites.
➢ We probably know that PHP can create dynamic websites, and PHP is quite easy to
learn when compared to other server-side languages. PHP is open-source, and its
components are free for usages and also easily available in the open-source market.
Hence opensource, we will use PHP. The free syntax is very easy to use. PHP runs all
type of Operating Systems like Windows, MacoX, Linux and Sun Solaris etc. it is one
of the main benefits of PHP.
➢ PHP supports all type of web servers like Apache Tomcat, IIS Servers, Jetty etc. This
facility will be more comfortable for PHP application developers to develop a flexible
environment that will save more time. Compared to other application programming
languages, PHP will be deployed more easily, and hosting companies for the PHP will
be more the server of the hosted companies for running the PHP applications will be
less costly.
➢ The Market of PHP Applications are taken as less effort when compared to other high
complexity applications. It is one of the best features of the PHP language. In the
Olden Days, the market of web applications will take more time to reaching the
market; it takes fewer chances of getting more popular in the market, and competition
also used to be more on that time. Performance-wise will be more reliable with the
user, so it is an effective language for user perspectives.
➢ PHP is also the same as compared to other languages like java; they have their own
predefined functions and libraries. It has the feature like sending emails, connect with
other network services it will generate jpeg, gif images etc., and also it generates pdf,
excels documents for downloading the web page contents in the applications.
➢ PHP applications are more user-friendly because it is easy to understand and it is
simplicity one

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -33-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Examples of Embed PHP in HTML


Given below are the examples:
Example #1
Code:
<html>
<title>First Application of PHP</title>
<body>
<h3>Welcome To My Domain</h3>
<?php
echo "Welcome User";
?>
</body>
</html>

Example #2
Code:
<html>
<title>Sample Application</title>
<body>
<h3>Welcome To My Domain</h3>
<?php
echo "Welcome Users.";
?>
<p>Welcome</p>
<?php
$examp = "Welcome Users";
echo " $examp.";
?>
</body>
</html>
Output:

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -34-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Example #3
Code:
<html>
<title>Sample Application</title>
<h3>Welcome To My Domain</h3>
<body>
<a href="first.php">Home</a>
<?php include "first.php";
?> <a href="second.php">contactus</a>
<?php include "second.php"
?>
</body>
</html>

First.php:
<?php
echo "Welcome"
?>

Second.php:
<?php
echo "User"
?>
Output:

➢ The above examples show about the PHP codes in html document.
➢ First two example, we write the basic html codes combined with the PHP tags; it will
show the output as a single web page HTML, but a final example will use the include
tag in the PHP tag; it will include the external PHP files like first and second.
➢ PHP files it is used to navigate the web pages from one page into another web page.

Embedding HTML in PHP:

<?php
$name = "Softmastx";
echo "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";
?>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -35-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Or
<?php
$array = array(1, 2, 3, 4);
?><table>
<thead><tr><th>Number</th></tr></thead>
<tbody>
<?php foreach ($array as $num) : ?>
<tr><td><?= htmlspecialchars($num) ?></td></tr>
<?php endforeach ?>
</tbody>
</table>

A better way!

Use ?>…<?php inside normal open and close tag.

<?php
$name = "Softmastx";?>
<div class="profile profile-user">
<h1>Hello User, </h1>
<p>Welcome to <?php echo $name;?></p>
</div>
<?php?>

Example:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "<table border='1'>";
echo "<tr><th>Day</th><th>Activity</th></tr>";
echo "<tr><td>Monday</td><td>Work</td></tr>";
echo "</table>";
break;
case "Tuesday":
echo "<table border='1'>";
echo "<tr><th>Day</th><th>Activity</th></tr>";
echo "<tr><td>Tuesday</td><td>Meeting</td></tr>";
echo "</table>";
break;
default:
echo "<p>No activity planned for this day.</p>";
}
?>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -36-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

To see how this works in practice, consider the following code listing:
<html>
<head>
<title>HTML Color Table</title>
<style type="text/css">
body {
font-family: Verdana sans-serif;
}
td {
border: solid 5px white;
}
</style>
</head>
<body>
<h2>Colors with HTML and PHP</h2>
<table>
<tr>
<td>Blue</td>
<td style="width:40px; background-color:#0000ff"></td>
</tr>
<tr>
<td><?php echo 'Red'; ?></td>
<td style="width:40px; background-color:<?php echo '#ff0000'; ?>"></td>
</tr>
<?php
// this row generated through PHP
echo "<tr>\n";
echo " <td>Green</td>\n";
echo " <td style=\"width:40px; background-color:#00ff00\"></td>\n";
echo "</tr>\n";
?>
</table>
</body>
</html>
➢ Save this script as colors.php, and view it in your Web browser. You should see an
HTML page containing a table with three rows and two columns, with one column
containing a color and the other its corresponding name (Figure 1-4).
➢ Use your browser’s View Source command to inspect the HTML code of the page,
and you’ll see that the PHP parser has interpolated the output of the various echo
statements into the HTML source code to create a complete HTML page. This is a

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -37-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

very common technique used for building Web applications with PHP, and you’ll see
it in almost every example that follows.

o
ESCAPING SPECIAL CHARACTERS
➢ There’s one interesting thing about colors.php that bears explaining: the numerous
backslashes used in the script. Look at the PHP-generated third row of the HTML
table, and then at the corresponding HTML source code of the output page, and you’ll
notice that none of these backslashes make an appearance. Where did they go?
➢ There’s a simple explanation for this. As you’ve already seen, output to be displayed
by PHP is wrapped in quotation marks. But what happens when the output to be
displayed includes quotation marks of its own, as occurs with the HTML code
generated in colors.php? If you simply enclose one set of quotation marks within
another, PHP will get confused about which quotation marks are to be printed
literally, and which ones are simply used to enclose the string value, and will generate
a parser error Therefore, to handle these situations, PHP allows you to escape certain
characters by preceding them with a backslash (\). There so-called escape sequences
include

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -38-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ When the parser encounters one of these escape sequences, it knows to replace it with
the corresponding value before sending it to the output device. Consider, for example,
this line of code:
<?php
echo "You said \"Hello\"";
?>
➢ PHP knows that the quotation marks preceded with a backslash are to be printed “as
is,” and it will not confuse them with the quotation marks that signal the beginning
and end of a string. This is why you see a backslash before every PHP-generated
quotation mark and line feed in colors.php.
Using Variables and Operators:
Storing data in variables:
➢ A variable is simply a container that’s used to store both numeric and non-numeric
information.
Variables:
➢ Every variable name must be preceded with dollar symbol and must begin with a
letter or underscore character, optionally followed by more letters, number or
underscore character.
➢ Common punctuations, characters such as commas, quotation marks or provide are
not permitted in variable name.
Ex:
$root, $_num, $query2 Valid
$58%, $1day, email Invalid
Assigning values to variables:
➢ Assigning a value to a variable in PHP is quite easy: use the equality symbols, which
also happens to be PHP’s assignment operator.
➢ This assigns the value on the right side of the equation to the variable on the left.
Ex:
$name=’PHP’;
$a=5;
Ex:
<?php
$new=2014;
$currentYear= $new;
$nextyear=$currentYear+1;
echo “$currentYear Ended Welcome to $nextyear”;
?>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -39-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Destroying Variables:
To destroy a variable, pass the variable to PHP’s aptly named unset() function.
Ex:
<?php
$car=’Porsche’;
//output: ‘before unset(), my car is a Porsche’
echo “before unset(), my car is a $car”;
//destroying variable
unset($car);
echo “after unset(), my car is a $car”;
?>
Inspecting Variables contents:
PHP offers var_dump() function which accept a variable and x-rays it for you.
Ex:
<?php
$name=’flora’;
$age=’25’;
var_dump($name);
var_dump($age);
?>

Understanding PHP data types:


➢ PHP supports data type like integer, float, and string, Boolean, null.
➢ Boolean are the simplest of all PHP data types.
Ex:
<?php
//Boolean
$validUser=true;
//Integer
$a=5;
//floating point
$temp=98.6;
//string
$cat=’NICE’;
//null
$here=null;
?>
● Booleans are the simplest of all PHP data types. Like a switch that has only two states, on
and off, it consists of a single value that may be set to either 1 (true) or 0 (false). In this
listing, $validUser is a Boolean variable set to true.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -40-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

● PHP also supports two numeric data types: integers and floating-point values.
Floatingpoint values (also known as floats or doubles) are decimal or fractional numbers,
while integers are round numbers.Both may be less than, greater than, or equal to zero. In this
listing, $size holds an integer value, while $temp holds a floating-point value.
● For non-numeric data, PHP offers the string data type, which can hold letters, numbers, and
special characters. String values must be enclosed in either single quotes or double quotes. In
the previous listing, $cat is a string variable containing the value 'Siamese'.
● You may also encounter the NULL data type, which is a “special” data type first
introduced in PHP 4. NULLs are used to represent “empty” variables in PHP; a variable of
type NULL is a variable without any data. In the preceding listing, $here is NULL.

Setting and checking variable data types:


➢ PHP automatically determines a variable’s data type from the content it holds.
➢ After if the variable’s content changes over the duration, the language will be
automatically set the variable to the new data type.
Ex:
<?php
$whoamI=’BCA’;
echo gettype ($whoamI);
$whoamI= 99.8;
echo gettype ($whoamI);
unset($whoamI);
echo gettype($whoamI);
?>
➢ gettype() operator, which is handy little tool for finding out the type of a
particular variable.
➢ which illustrates turning a floating-point value into an integer value:
<?php
// define floating-point variable
$speed = 501.789;
// cast to integer
$newSpeed = (integer) $speed;
// output: 501
echo $newSpeed;
?>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -41-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Constants:
➢ Constants are containers for values that remain constants and never change.
➢ They are mostly used for data that is known well in advance and that is used,
unchanged, in multiple places within your application.
➢ Constants are defined using PHP’s define() function, which accepts two arguments.
✓ Name of the constant
✓ Its value
➢ Constants names must follow the same rules of variable names, with one exception
$prefix is not required for constant names.
Ex:
<?php
define (‘program’, ‘the matrix’);
define(‘version’,11.7);
echo ‘welcome to’. program.’(version’. version.’)’;
?>
Manipulating Variables with Operators:
➢ Operators are symbols that tell the PHP processor to perform certain actions.
Ex:
Addition (+) is an operator that tells the PHP to add two variables, which the greater than
(>) is an that tells PHP to compare the two values
➢ PHP support more than 50 such operators for arithmetical operations, logical
comparisons and bitwise calculations.
Performing Arithmetic operators:
PHP supports all standard arithmetic operations.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Divide and return quotient
% Divide and return modulus
Ex:
<?php
$x=10;
$y=15;
$z=20;
$sum=$x + $y;
echo “$x + $y=$sum\n”;
$sub=$x - $y;
echo “$x - $y=$sub\n”;
$mul=$x * $y;
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -42-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

echo “$x * $y=$mul\n”;


$div=$x / $y;
echo “$x / $y=$div\n”;
$modulus=$x % $y;
echo “$x % $y=$modulus\n”;
?>
Concatenating Strings:
To combine strings, use PHP’s concatenation operator, which happens to be a period (.).
Ex:
<?php
$country=’England’;
$city=’London’;
//combine into a single string
//output: ‘Welcome to London, the coolest city in all of England’;
echo ‘Welcome to’ .$city. ‘the coolest city in all of ‘.$country;
?>
Comparing Variables:
PHP lets you compare one variable or value with another via its wide range of comparison
operators.
Ex:
<?php
$p=10;
$q=11;
$r=11.3;
$s=11;
echo ($q>$p);
echo ($q<$p);
echo ($q>=$s);
echo ($r<=$s);
Operators Descriptions
== Equal to
=! Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
=== Equal to and of the same type

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -43-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Ex:
<?php
$bool= (Boolean) 1;
$int= (integer) 1;
echo ($bool= =$int);
echo ($bool= = =$int);
?>
(= = =) This operator allows for stricter comparison between variable: it only return
true if the two variables or value being compared hold the same information and are of the
same data type.
Performing Logical test:
PHP supports the logical operators.
Operator Description
&& AND
|| OR
! NOT
Ex:
<?php
$price=100;
$size=18;
echo ($price>50&&$size<25);
echo ($price>150||$size>75);
echo !($size>10);
?>

Other useful operators:


➢ There are few other operators that tend to come in handy during PHP development.
➢ The addition assignment operator, represented by the symbol +=, lets you
simultaneously add and assign a new value to a variable.

Operator Description
+= Add and assign
-= Subtract and assign
*= Multiplication and assign
/= Divide and assign quotient
%= Divide and assign modulus
.= Concatenate and assign
(strings only)

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -44-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Ex:
<?php
$count=7;
$age=60;
$greeting=’we’;
$count-=2;
echo $count;
$age/=5;
echo $age;
$greeting .= ‘lcome’;
echo $greeting;
?>
Auto increment and decrement operator:
➢ It can be represented by ++ and – symbols.
➢ The operator automatically add one, two, subtract 1 from, the variables they are applied
to.
Ex:
<?php
$count=19;
$count++;
echo $count;
$count --;
echo $count;
?>

Understanding Operator Precedence:


➢ BODMAS it represent the order in which a calculator or a computer perform a
sequence of mathematical operations: Brackets, Order, Division, Multiplications,
Addition and Subtraction.
➢ The following list illustrates PHP’s most important precedence rules.
➢ Operators at the same level have equal precedence.
1. ++ --
2. !
3. */%
4. +-.
5. < <= > >=
6. = = != = = = != =
7. &&
8. ||
9. = += -= *= /= .= %= &= |= ^=
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -45-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Ex:
(((4*8)-2)/10)
((((32)-2)/10) with parenthesis
((30)/10)
3
4*8-2/10
32-0.8 without parenthesis
31.8
Example Program:

Building a Dollars-to-Euros Converter Here’s the code (convert.php):


<html>
<head>
<title>Project 2-1: USD/EUR Currency Conversion</title> </head>
<body>
<h2>Project 2-1: USD/EUR Currency Conversion</h2>
<?php
// define exchange rate
// 1.00 USD = 0.70 EUR
define ('EXCHANGE_RATE', 0.70);
// define number of dollars
$dollars = 150;
// perform conversion and print result
$euros = $dollars * EXCHANGE_RATE;
echo "$dollars USD is equivalent to: $euros EUR"; ?>
</body> </html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -46-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Handling form Input:


<html>
<head> </head>
<body>
<h2>Select your car</h2>
<form method=”post” action=”car.php”>
Type:<br/>
<select name=”selType”>
<option value=”Porsche 911”>Porsche 911</option>
<option value=”Volkswagen Beetle”>Volkswagen Beetle</option>
<option value=”Ford Taurus”>Ford Taurus</option>
</select><p/>
Color:<br/>
<input value=”text”name=”txtColor” /><p/>
<input value=”submit/>
</form> </body>
</html>
<html>
<head> <title> </title>
<body>
<h2>Success!</h2>
<?php
//get form input
$type=$_POST [‘selType’];
$color=$_POST [‘txtColor’];
echo “Your $color $type is ready. Safe Driving!”;
?>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -47-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Example 3: Building an Interactive HTML Color Sampler


First up, the Web form (color.html):
<html>
<head>
<title>Project 2-2: An Interactive HTML Color Sampler</title>
</head>
<body>
<h2>Project 2-2: An Interactive HTML Color Sampler</h2>
<form method="get" action="display.php">
R: <input type="text" name="r" size="3" /> <p />
G: <input type="text" name="g" size="3" /> <p />
B: <input type="text" name="b" size="3" /> <p />
<input type="submit" value="Show me" />
</form>
</body>
</html>
The PHP script that accepts the input and uses it to display a color swatch (display.php):
<html>
<head>
<title>Project 2-2: An Interactive HTML Color Sampler</title>
</head>
<body>
<h2>Project 2-2: An Interactive HTML Color Sampler</h2>
<?php
// get input values
$r = $_GET['r'];
$g = $_GET['g'];
$b = $_GET['b'];
// generate RGB string from input
$rgb = $r . ',' . $g . ',' . $b;
?>
R: <?php echo $r; ?>
G: <?php echo $g; ?>
B: <?php echo $b; ?>
<p />
<div style="width:150px; height: 150px;
background-color: rgb(<?php echo $rgb; ?>)" />
</body> </html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -48-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

WRITING SIMPLE CONTITIONAL STATEMENTS

In addition to storing and retrieving value in variables, PHP also lets


programmers evaluate different conditions during the course of a program and take decisions
based on whether these conditions evaluate to true or false. These conditions, and the actions
associated with them, are expressed by means of a programming construct called a
conditional statement. PHP supports different types of conditional statements, each one
intended for a particular use.
i) The if statement
➢ The simplest of PHP’s conditional statements is the if statement.
➢ This works much like the English-language statement, “if X happens, do Y.” here’s a
simple example, which contains a conditional statement that checks if the value of the
$number variable is less than 0 and prints a notification message if so.
Syntax:
if(expression)
statement
➢ A Boolean value is one that can be reduced to one of two values : True or False
if(expression)
{
Statement 1;
Statement 2;
}

Example:
<?php
// if number is less than zero
//print message
$number = - 88;
if ($number < 0)
{
echo ‘That number is negative’ ;}
?>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -49-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ The key to the if statement is thus the condition to be evaluated, which is always
enclosed in parentheses.

ii) The if-else statement


➢ The if statement is quite basic: it only lets you define what happens when the
conditions specified evaluates to true.
➢ But PHP also offers the if –else statement, an improved version of the if construct that
allows you to define an alternative set of action that the program should take when the
condition specified evaluates to false.
➢ In English, this statement would read, “if X happens, do Y; otherwise, do Z.”
Syntax :
if(expression)
{
Statement 1;
else
Statement 2;
}

Example:
<?php
//change message depending on whether
//number is less than zero or not
$number =-88;
if ($number<0)
{echo ‘that number is negative’;}
else
{echo ‘that number is either positive or zero’;}
?>
➢ Here, an if –else statements is used to account for two possible outcomes: a number
less than zero, and all other number.
Example Program: Testing Odd and Even Numbers
Here’s the code (oddeven.php):
<html>
<head>
<title>Project 3-1: Odd/Even Number Tester</title>
</head>
<body>
<h2>Project 3-1: Odd/Even Number Tester</h2>
<?php
// if form not yet submitted
// display form
if (!isset($_POST['submit'])) {
?>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -50-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

<form method="post" action="oddeven.php">


Enter value: <br />
<input type="text" name="num" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
// if form submitted
// process form input
} else {
// retrieve number from POST submission
$num = $_POST['num'];
// test value for even-ness
// display appropriate message
if (($num % 2) == 0) {
echo 'You entered ' . $num . ', which is an even number.';
} else {
echo 'You entered ' . $num . ', which is an odd number.';
}}
?>
</body>
</html>

➢ The if –else statement lets you define actions for two eventualities: a true condition
and a false conduction. The if -elseif-else statement and the switch –case statements.
iii) THE IF -ELSEIF-ELSE STATEMENT
➢ The if -elseif-else statement lets you chain together multiple if –else statements, thus
allowing the programmer to define actions for more than just two possible outcomes.
Consider the following examples , which illustrates its use:

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -51-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Syntax:
if(expression)
{
Statement 1;
{
elseif(expression 2)
{
Statement 2;
}
elseif(expression 3)
{
Statement 3;
}
else
{
Statement 4;
}

Example:
<?php
//handle multiple possibilities
//define a different message for each day $today=’Tuesday’;
if ($today == ‘Monday’)
{
echo ‘Monday\’s child is fair of face. ’;}
elseif ($today == ‘Tuesday’) {
echo ‘Tuesday\ ‘s child is full of grace. ‘;}
elseif ($today == ‘Wednesday’){
echo ‘Wednesday\ ‘s child is full of woe.’ ;}
elseif ($today == ‘Thursday’){
echo ‘Thursday\ ‘s child has far to go.’ ;}
elseif ($today == ‘Friday’){
echo ‘Thursday\ ‘s child is loving and giving.’ ;}
elseif ($today == ‘Saturday’){
echo ‘Thursday\ ‘s child works hard for a living.’ ;}
else{ echo ‘No information available for that day’;}
?>
Here, the program will output a different message for each day of the week (as set in the
$today variable).

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -52-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Example : Assigning Boy Scouts to Tents


Here’s the code (tent.php):
<html>
<head>
<title>Project 3-2: Tent Assignment</title>
</head>
<body>
<h2>Project 3-2: Tent Assignment</h2>
<?php
if (!isset($_POST['submit'])) {
?>
<form method="post" action="tent.php">
Enter your age: <br />
<input type="text" name="age" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
} else {
$age = $_POST['age'];
if ($age <= 9) {
echo "You're in the Red tent.";
} elseif ($age > 9 && $age <= 11) {
echo "You're in the Blue tent.";
} elseif ($age > 11 && $age <= 14) {
echo "You're in the Green tent.";
} elseif ($age > 14 && $age <= 17) {
echo "You're in the Black tent.";
} else {
echo "You'd better get in touch with the Scoutmaster.";
}
}
?>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -53-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

UNIT – III

Switch( ) Statements -Using the while( ) Loop- Using the for( ) Loop PHP
Functions. PHP Functions – Creating an Array Modifying Array Elements-Processing
Arrays with Loops-Grouping Form Selections with Arrays-Using Array Functions.

THE SWITCH-CASE STATEMENT:


An alternative to the if-elseif-else statement is the switch-case statement, which
does almost the same thing: it tests a variable against a series of values until it finds a match,
and then executes the code corresponding to that match. Consider the following code listing,
which is equivalent to the preceding one:
Syntax :

switch(exp)
{
case label value 1 : statement 1;
break;
case label value 2 : statement 2;
break;
------
------
case label value n : statement n;
break;
default: statement -x;
}

Ex:
<?php
$today = ‘Tuesday’ ;
switch ($today)
{
case ‘Monday’ :
echo ‘Monday\ ‘s child is fair of face. ‘ ;
break;
case ‘Tuesday’ :
echo ‘Tuesday\ ‘s child is full of grace. ‘ ;
break;
case ‘Wednesday’ :
echo ‘Wednesday\ ‘s child is full of woe. ‘ ;
break;
case ‘Thursday’ :
echo ‘Thursday\ ‘s child is far to go. ‘ ;
break;
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -54-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

case ‘Friday’ :
echo ‘Friday\ ‘s child is loving and giving. ‘ ;
break;
case ‘Saturday’ :
echo ‘Saturday\ ‘s child is works hard for a living. ‘ ;
break;
default:
echo ‘No information available for that day’;
}
?>

The switch-case construct differs from the if-elseif-else construct in one important way.
Once PHP finds a case statement that evaluates to true, it executes not only the code
corresponding to that case statement, but also the code for all subsequent case statements. If
this is not what you want, add a break statement to the end of each case block (as is done in
the previous listing) to tell PHP to break out of the switch-case statement block once it
executes the code corresponding to the first true case.
Notice also the ‘default’ case: as the name suggests, this specifies the default set of
actions PHP should take if none of the other cases evaluate to true. This default case, like the
else branch of the if-elseif-else block, is very useful as a “catch-all” handler for unforeseen
situations.

COMBINING CONDITIONAL STATEMENTS


PHP allows one conditional statement to be nested within another, to allow for more
complex decision-making. To illustrate this, consider the following listing:
<?php
// for employees with annual comp <= $15000
// those with a rating >= 3 get a $3000 bonus
if ($rating >= 3) {
if ($salary < 15000) {
$bonus = 5000 ;
}
}
else {
if ($salary < 15000)
{
$bonus = 3000 ;
}
}
?>
You can also combine conditional statements by using logical operators, such as the &&
or || operator. You learned about logical operators in the preceding chapter; Table 3-2 quickly
recaps the list.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -55-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Here’s an example of how these logical operators can be used with a conditional
statement:
<?php
$year = 2008;
// leap years are divisible by 400
// or by 4 but not 100
if (($year % 400 == 0) || (($year % 100 !=0) && ($year % 4 == 0)))
{
echo “$year is a leap year.”;
}
?>

LOOPING STATEMENTS

i) THE WHILE LOOP


The easiest type of loop to understand is the while loop, which repeats continuously while
a prespecified condition is true. Here’s an example, which uses a loop to repeatedly print an
‘X’ to the output page.
Syntax :
while(con)
{
body of the loop statements;
}
Ex:
<?php
// repeat continuously until counter become 10
// output : ‘XXXXXXXXXXX’
$counter = 1;
while ($counter < 10)
{
echo ‘x’ ;
$counter++;
}
?>

ii) THE DO-WHILE LOOP


With a while loop, the condition to be evaluated is tested at the beginning of each loop
iteration. There’s also a variant of this loop, the do-while loop, the do-while loop, which
evaluates the condition at the end of each loop iteration.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -56-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Syntax:
do
{
body of the looping statements;
}
while (con);
Ex:
<?php
// repeat continuously until counter become 10
// output : ‘XXXXXXXXXXX’
$counter = 1;
do
{
echo ‘x’ ;
$counter++;
}
while ($counter < 10);
?>

iii) THE FOR LOOP


The while and do-while loops are firely simple: they repeat for so long as the specified
condition remains true. But PHP also supports a more sophisticated type of loop, the for loop,
which is useful when you need to execute a set of statements a specific number of times.
Syntax:
for ( initialize ; condition ; inc/dec)
{
body of the looping statement;
}
The best way to understand a for loop is by looking at some code. Here’s simple example,
Which lists the numbers between 1 and 10.
<?php
// repeat continuously until counter becomes 10
// output: ‘XXXXXXXXX’
for ($x=1; $x<10; $x++)
{
echo “$x”;}
?>
• The first of this is an assignment expression, which initialize the loop counter to a
specific values--- in this case, assigning the value 1 to the variable $x.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -57-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

• The second is a conditional expression, which must evaluate to either true or


false; the loop will continue to execute so long as this condition remains true.
Once the condition becomes false, the loop will stop executing.
• The third is again an assignment expression, which is executed at the end of each
loop iteration, and which updates the loop counter with a new value – in this case,
adding 1 to the value of $x.

<?php
// generate ordered list of 6 times
echo “<01>”;
for ($x=1; $x<7; $x++)
{
echo “<li>Item $x</li>”;
}
echo “ </01>”;
?>
iv) COMBINING LOOPS
Just as with conditional statements, it’s also possible to nest one loop inside another. To
illustrate, consider the next example, which nests one for loop inside another loop to
dynamically generate an HTML table.
Example:
<html>
<head>
<title></title>
</head>
<body>
<?php
// generate an HTML table
// 3 rows, 4 columns
echo “<table border= \”1\”>”;
for ($row =1 ; $row<4; $row++)
{
echo “<tr>”;
for ($col =1; $col<5; $col++)
{
echo “<td>Row $row, column $col< /td>”;
}
echo “</tr>”;
}
echo “</table>”;
?>
</body> </html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -58-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Output:

Row 1, Column 1 Row 1, Column 2 Row 1, Column 3 Row 1, Column 4


Row 2, Column 1 Row 2, Column 2 Row 2, Column 3 Row 2, Column 4
Row 3, Column 1 Row 3, Column 2 Row 3, Column 3 Row 3, Column 4

V) INTERRUPTING AND SKIPPING LOOPS


While on the topic of loops, it’s interesting to discuss two PHP statements that allow you
to either interrupt a loop or skip a particular iteration of a loop. PHP’s break statement is
aptly named: it allows you to break out of a loop at any point
Example:
<?php
$count = 0;
// loop 5 times
while ($count <= 4)
{
$count++;
// when the counter hits 3
// breakout of the loop
if ($count == 3)
{
Break;
}
echo “this is iteration #$count <br/>”;
}
?>
Example: Break and continue
<?php
$count = 0;
//loop 5 times
while ($count <= 4)
{
$count++;
// when the counter hits 3
// skip to the next iteration
if($count == 3)
{
continue;
}
echo “this is iteration #$count <br/>”;
}
?>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -59-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Example Program: Building a Factorial Calculator


Here’sthe code (factorial.php):
<html>
<head>
<title>Project 3-3: Factorial Calculator</title>
</head>
<body>
<h2>Project 3-3: Factorial Calculator</h2>
<?php
if (!isset($_POST['submit'])) {
?>
<form method="post" action="factorial.php">
Enter a number: <br />
<input type="text" name="num" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
} else {
$num = $_POST['num'];
if ($num <= 0) {
echo 'ERROR: Please enter a number greater than 0';
exit();
}
$factorial = 1;
for ($x=$num; $x>=1; $x--) {
$factorial *= $x;
}
echo "Factorial of $num is: $factorial";
}
?>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -60-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

CREATING USER-DEFINED FUNCTIONS


User-defined functions are a neat way for you to create independent, reusable code
“package”
Packaging your code into functions has four important advantages:
➢ It reduce duplication within a program, by allowing you to extract commonly
used routines into a single components.
➢ A function is created once but use many times often from more than one
program. If the function code changes, the changes are implemented in one
spot(the function definition) while the function invocations remain untouched.
➢ Debugging and testing a program becomes easier when the program is
subdivided into functions.
➢ Functions encourage abstract thinking, because packaging program code into a
function is nothing more or less than understanding how a specific task may
be encapsulated into a generic component.

CREATING AND INVOKING FUNCTIONS


There are three components to every function:
➢ Arguments, which serve as inputs to the function.
➢ Return values, which are the output returned by the functions.
➢ The function body, which contains the processing code to turn inputs into
outputs.

Consider the following PHP script, which contains a user-defined function to print the current
day of the week:
<?php
// function definition
// print today’s weekday name
function whatIsToday()
{
echo “today is “ . date(‘1’ , mktime());
}
//function invocation
whatIsToday();
?>
Function definitions begin with the function keyword, followed by the functions name and a
lis of arguments in parentheses.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -61-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

USING ARGUMENTS AND RETURN VALUES


A function that always returns the same output is a lot like a radio station that plays
the same song all day. Where arguments come in arguments are “placeholder” variables
within a function definition. The processing code within the function then manipulates these
values to return the desired result.
<?php
// function definition
//calculate perimeter of rectangle
//p= 2*(1+w)
function getperimeter ($length , $width)
{
$perimeter=2*($length + $width);
echo “ The perimeter of a rectangle of length $length
unite and width $width units is: $perimeter units”;
}
// functions invocation
// with arguments
getPerimeter(4,2);
?>
The function in this listing performed a calculation and then printed the result directly
to the output page.
<?php
// function definition
// calculate perimeter of rectangle
// p = 2 * (l+w)
function getPerimeter($length, $width) {
$perimeter = 2 * ($length + $width);
return $perimeter;
}
// function invocation
echo 'The perimeter of a rectangle of length 4 units
and width 2 units is: ' . getPerimeter(4,2) . ' units';
?>
SETTING DEFAULT ARGUMENT VALUES:
The arguments that a function excepts to receive from the main program are
specified in the function’s argument list. For convenience, you can assign default values to
any or all of these arguments.
<?php
// function definition
// generate e-mail address from supplied values
function buildAddress($username, $domain= ‘mydomain.info’)
{
return $username . ‘@’ . $domain;
}
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -62-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

// function invocation
// without optional argument
//output: ‘My e-mail address is john@domain.info’
echo ‘my e-mail address is ‘ . buildaddress(‘john’);
// function invocation
// with optional argument
// output: ‘my e-mail address is jane@cooldomain.net’
echo ‘my e-mail address is ‘ . buildAddress(‘jane’ , ‘cooldomain.net’);
?>
Notice that in the first instance, the function has been called with only a single argument,
even though the function definition requires two.

USING DYNAMIC ARGUMENT LISTS


A PHP function definition normally has a fixed argument list, where the number of
arguments is known in advance. PHP also lets you define functions with so-called variable-
length argument lists.
<?
//* function definition
// calculate average of supplied values
function calcAvergae()
{
$args = func_get_args();
$count = func_num-args();
$sum= array_sum($args);
$avg = $sum / $count;
return $avg;
}
// function invocation
// with 3 arguments
// output: 6
echo calcAverage(3,6,9);
// function invocation
// with 8 arguments
// output: 150
echo calcAverage(100,200,100,300,50,150,250,50);
?>
Note, that the CalcAverage() function definition in the previous listing does not include a
predefined argument list.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -63-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

UNDERSTANDING VARIABLE SCOPE:


A key concept related to user defined function in PHP is variable scope: the extent of a
variable’s visibility within the space of a PHP program. By default, variables used within the
function are local-their impact is restricted to the function space alone.
<?php
//function definition
//change the value of $score
function changeScore()
{
$score=25;
}
//define a variable in the main program
//print its value
$score=11;
echo ‘Score is:’.$score; //output:11
//run the changeScore() function
changeScore();
//print $score again
echo ‘Score is:’.$score; //output:11
?>

USING RECURSIVE FUNCTIONS:


Another, slightly more complex idea involving functions is recursion. The recursive function
is a function that calls itself repeatedly until a condition is satisfied.
<?php
//recursive function definition
//function to print all the values
//in a nested array
function printValues ($arr))
{
global $count;
global $out;
//check that input is an array
if(!is_array($arr)){
die(‘ERROR: Input is not an array’);
}
//iterate through array
//increment counter by 1 for each value found
//if value is itself an array:
//recursively call function to count
//number of elements in the child array
//else:
//add the value found to the output array
foreach($arr as $a){
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -64-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

if(is_array($a)){
printValues($a);
}else{
$out[]=$a;
$count++;
}
}
//return total count and values found to caller
//as array
return array(‘total’=>$count,’values’=>$out);
}
//define nested array
$data=array(
‘o’=>array(
‘orange’,
‘owl’,
‘one’),
‘t’=>array(
‘tea’,
‘ten’,
‘tag’,
‘twentythree’=>array(
array(‘twenty’,’three’),
array(‘vingt’,’trois’,array(
‘red’=>’baron’,
‘blue’=>’blood’
))
)
)
);
//count and print values in nested array
$ret=printValues($data);
Echo $ret[‘total’].’value(s) found:’;
Echo implode(‘,’,$ret[‘values’]);
?>
o/p
12 value(s) found: orange, owl, one, tea, ten,
tag, twenty, three, vingt, trois, baron, blood

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -65-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Example Program : Calculating GCF and LCM


Here’s the code (gcf_lcm.php):
<?php
function getGCF($a, $b) {
if ($b == 0) {
return $a;
}
else {
return getGCF($b, $a % $b);
}
}
function getLCM($a, $b) {
return ($a * $b) / getGCF($a, $b);
}
?>

<html>
<head>
<title>Project 5-1: GCF and LCM</title>
</head>
<body>
<h2>Project 5-1: GCF and LCM</h2>
<?php
if (!isset($_POST['submit'])) {
?>
<form method="post" action="gcf_lcm.php">
Enter two integers: <br />
<input type="text" name="num_1" size="3" />
<p>
<input type="text" name="num_2" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
} else {
$num1 = (int)$_POST['num_1'];
$num2 = (int)$_POST['num_2'];
echo "You entered: $num1, $num2";
echo "<br />";
echo "The GCF of ($num1, $num2) is: " . getGCF($num1, $num2);
echo "<br />";
echo "The LCM of ($num1, $num2) is: " . getLCM($num1, $num2);
}
?>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -66-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

WORKING WITH ARRAYS

STORING DATA IN ARRAYS:


Array variables are “special” because they can hold more than one value at a time.
• This makes them particularly useful for storing related values.
• Use index numbers to access the various values stored inside it, with zero representing
the first value.
<?php
$fruits=array('apple','banana','pineapple','grape');
?>
<?php
$fruits=array('a'=>'apple',
'b'=>'banana',
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -67-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

'p'=>'pineapple',
'g'=>'grape');
?>
• This type of array is known as an associative array.
$fruits [‘a’] =’apple’;
$fruits [‘b’] =‘banana';
$fruits [‘p’] ='pineapple';
$fruits [‘g’] ='grape';

• The keys of the array must be unique;


• Each key references a single value, and the key-value relationship is expressed
through the => symbol.

ASSIGNING ARRAY VALUES:


Variable names must be preceded with a dollar ($) symbol and must begin with
a letter or underscore character, optionally followed by more letters, numbers,or underscore
characters.
• Punctuation characters and spaces are not allowed within array variable names.
There are two ways of assigning values to it, where the values are all assigned at once,
separated with commas. This method creates a standard, number indexed array.
<?php
$cars=array('ferrari',
'porsche',
'jaguar',
'lamborghini',
'mercedes');
?>
• To create such an array is to set values individually using index notation.
<? php
$cars [0] ='Ferrari';
$cars [1] ='Porsche';
$cars [2] ='jaguar';
$cars [3] ='Lamborghini';
$cars [4 ]='Mercedes';
?>
You can also use both these techniques with associative arrays. To assign all the
values of such an array in a single statement, set a key for each value and link the two using
the => connector, remembering to separate each key-value pair with commas. Here’s an
example:
<?php
// define array
$data = array(
'username' => 'john',
'password' => 'secret',
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -68-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

'host' => '192.168.0.1'


);
?>
You can also assign values to keys one by one, as in this next example:
<?php
// define array
$data['username'] = 'john';
$data['password'] = 'secret';
$data['host'] = '192.168.0.1';
?>
To access a value from an array in a script, simply use the array name and index/key
in an
expression and PHP will replace it with its value when the script is executed, as with any
normal variable.
Here’s a simple example that illustrates how this works:
<?php
// define array
$data = array(
'username' => 'john',
'password' => 'secret',
'host' => '192.168.0.1'
);
// use array value
echo 'The password is: ' . $data['password'];
?>

MODIFYING ARRAY VALUES:


Simply assign a new value to the element using either its index or its key.
<? php
$meats=array ('fish','chicken','ham','lamb');
$meats [2] ='turkey';
?>
• To remove an element from an array, use the unset () function on the corresponding
key or index.
<? php
$meats=array ('fish','chicken','ham','lamb');
Unset ($meats [0]);
?>

RETRIEVING ARRAY SIZE:


An important task when using arrays, especially in combination with loops, is
finding out how many values the array contains.
<?php
$data=array ('mondat','tuesday','wednesday');
echo 'this array has ' . count ($data) . ' elements';
?>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -69-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

o/p
This Array Has 3 Elements
• This is easily accomplished with PHP’s count () function, which accepts the array
variable as a parameter and returns an integer value indicating how many elements it
contains.

NESTING ARRAYS:
PHP also allows you to combine arrays, by placing one inside another to an
unlimited depth
• When dealing with structured, hierarchically arranged information.
$phonebook=array(arrays (‘name’=>’ram’,
‘tel’=>9556564654”,
‘email’=>’ram@gmail.com’,),
Arrays (‘name’=>’Davind’,
‘tel’=>95565986412”,
‘email’=>’davind@gmail.com’,),
Arrays (‘name’=>’kavin’,
‘tel’=>95565696585”,
‘email’=>’kavin@gmail.com’,));
• $phonebook is an array nested two levels deep. The first level is numerically indexed,
with each element representing an entry from a phone book
$phonebook=array(arrays (‘name’=>’ram’,
‘tel’=>9556564654”,
‘email’=>’ram@gmail.com’,),
Arrays (‘name’=>’Davind’,
‘tel’=>95565986412”,
‘email’=>’davind@gmail.com’,),
Arrays (‘name’=>’kavin’,
‘tel’=>95565696585”,
‘email’=>’kavin@gmail.com’,));
echo "davind number is:" . $phonebook[1]['tel']; ?>
• Each of these elements is itself an associative array, holding specific information on
the attributes of the corresponding phone book entry, such as the contact’s name,
phone number and e-mail address.

PROCESSING ARRAYS WITH LOOPS AND ITERATORS:


Performing an operation or calculation on each value it finds.A for loop
iterates over the $cities array, printing each value found. The loop runs as many times as
there are elements in the array.
The for each loop:

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -70-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

$cities=array('londin','paris','madrid','los angeles','bombay','jakarta');
for ($i=0;$i<count($cities);$i++)
{
echo $cities[$i] . "\r\n";
}
?>
O/p
Londin paris madrid los angeles bombay jakarta

FOR EACH LOOP


With a foreach loop, each time the loop runs, the current array element is
assigned to a temporary variable, which can then be processed in any way you please-printed,
copied to another variable, used in a calculation
<?php
$cities=array('londin','paris','madrid','los angeles','bombay','jakarta');
foreach($cities as $c)
{
echo "$c \r\n";
}
?>
o/p
londin paris madrid los angeles bombay Jakarta

THE ARRAY ITERATOR


You may prefer to use an ArrayIterator which provides a ready-made, extensible
tool to loop over array elements.
• An ArrayIterator object is initialized with an array variable and the object’s rewind ()
method is used to reset the internal array pointer to the first element of the array.
• A while loop, which runs so long as a valid () element exists, can then be used to
iterate over the array.
<?php
$cities=array("united Kingdom" =>"london",
"unites states"=>"washington",
"france"=>"paris",
"india"=>"Delhi");
$iterator = new ArrayIterator($cities);
$Iterator->rewind();
while($iterator->valid())
{
print $iterator->current() . " is in " . $iterator->key() . ". \r\n";
$iterator->next();
}
?>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -71-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

• Individual array keys are retrieved with the key () method, and their corresponding
values are retrieved with the current () method. The next () method moves the
internal array pointer forward to the next array element.

Example Program : Averaging the Grades of a Class


Here’s the code (grades.php):
<html>
<head>
<title>Project 4-1: Grade Averaging</title>
</head>
<body>
<h2>Project 4-1: Grade Averaging</h2>
<?php
// define array of grades
// ranging between 1 and 100
$grades = array(
25, 64, 23, 87, 56, 38, 78, 57, 98, 95,
81, 67, 75, 76, 74, 82, 36, 39,
54, 43, 49, 65, 69, 69, 78, 17, 91
);
// get number of grades
$count = count($grades);
// iterate over grades
// calculate total and top/bottom 20%
$total = $top = $bottom = 0;
foreach ($grades as $g) {
$total += $g;
if ($g <= 20) {
$bottom++;
}
if ($g >= 80) {
$top++;
}
}
// calculate average
$avg = round($total / $count);
// print statistics
echo "Class average: $avg <br />";
echo "Number of students in bottom 20%: $bottom <br />";
echo "Number of students in top 20%: $top <br />";
?>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -72-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

GROUPING FORM SELECTION WITH ARRAY:


Arrays are particularly potent when used in combination with form elements that
support more than one value, such as multiple-selection list boxes or grouped checkboxes.
<form method="post" action="array-form.php">
select your favourite artists: <br />
select name="artists[]" multiple="true">
<option value="vijaya">vijay</option>
<option value="ajith">ajith</option>
<option value="suriya">suriya</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>

Example Program : Selecting Pizza Toppings Here’s the form (pizza.html):


<html>
<head>
<title>Project 4-2: Pizza Topping Selector</title>
</head>
<body>
<h2>Project 4-2: Pizza Topping Selector</h2>
<form method="post" action="pizza.php">
Select your favourite pizza toppings: <br />
<input type="checkbox" name="toppings[]" value="tomato">Tomato</input>
<input type="checkbox" name="toppings[]" value="onion">Onion</input>
<input type="checkbox" name="toppings[]" value="jalapenos">Jalapeno
peppers</input>
<input type="checkbox" name="toppings[]" value="olives">Olives</input>
<input type="checkbox" name="toppings[]" value="mint">Mint</input>
<input type="checkbox" name="toppings[]" value="pineapple">Pineapple</input>
<input type="checkbox" name="toppings[]" value="bacon">Bacon</input>
<input type="checkbox" name="toppings[]" value="chicken">Chicken</input>
<input type="checkbox" name="toppings[]" value="ham">Ham</input>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -73-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

<input type="checkbox" name="toppings[]" value="anchovies">Anchovies</input>


<input type="checkbox" name="toppings[]" value="x-cheese">Extra cheese</input>
<p>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
And here’s the code for the form submission script (pizza.php):
<html>
<head>
<title>Project 4-2: Pizza Topping Selector</title>
</head>
<body>
<h2>Project 4-2: Pizza Topping Selector</h2>
You selected the following toppings: <br />
<ul>
<?php
foreach ($_POST['toppings'] as $t) {
echo "<li>$t</li> \r\n";
}
?>
</ul>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -74-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

WORKING WITH ARRAY FUNCTIONS:

PHP has numerous built-in- array manipulation functions, supporting operations ranging
from array search and comparison to sorting and conversion operations

Function What it does


explode () splits a string into array elements
implode () joins array elements into a string
range() generate a number range as an array
min () finds the smallest value in an array
max () finds the largest value in an array
shuffle () randomly rearranges the sequence of elements in an
array
array_pop () removes an element from the end of an array
array_push () adds an element to the end of an array
array_unique () removes duplicate elements from an array
array_reverse () reverses the sequence of elements in an array
array_merge () combines two or more arrays
array_diff () calculates the difference between two arrays
sort () sorts an array
assort () sorts an associative array by value
ksort () sorts an associative array by value

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -75-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Converting between strings and array:


PHP lets you convert a string into an array, by splitting the string on a user-defined
separator and assigning the resulting segments to an array.
<?php
$str='tinker,tailor,soldier,spy';
$arr=explode(',',$str);
print_r($arr);
?>
O/p
Array ( [0] => tinker
[1] => tailor
[2] => soldier
[3] => spy )

• Explode () function, which accepts two arguments-the separator and the source string-
and returns an array.
<?php
$arr=array('one,two,three,four');
$str=implode('and',$arr);
print_r($str);
?>
O/p
one,two,three,four
• It’s also possible to reverse the process, joining the elements of an array into a single
string using user-supplied “glue”.

WORKING WITH NUMBER RANGES:


To fill an array with a range of numbers, the range () function offers a convenient
alternative tomanually entering each value.

<?php
$arr=range(1,5);
print_r($arr);
?>
o/p
Array ( [0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5 )
• This function accepts two end points and returns an array containing all the numbers,
between those end points.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -76-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

• If you already have an array of numbers and are trying to calculate the minimum or
maximum of the series, PHP’s min() and max() functions will come in handy-they
accept an array of numbers and return the smallest and largest values in the array
respectively.
<?php
$arr=array(7,36,5,48,28,90,91,3,67,42);
echo 'minimum is ' . min($arr) . ' and maximum is ' . max($arr);
?>
O/p
minimum is 3 and maximum is 91

EXTRACTING ARRAY SEGMENTS:


PHP allows you to slice an array into smaller parts with the array_slice() function
<?php
$arr=array('voilet','indigo','blue','green','yellow','orange','red');
$arr1=array_slice($arr,2,3);
print_r($arr1);3
?>
O/p
Array ( [0] => blue
[1] => green
[2] => yellow )

ADDING AND REMOVING ARRAY ELEMENTS:


PHP comes with four functions that allow you to add or remove elements from the
beginning or end of an array.
• The array_unshift () function adds an element to the beginning of an array.
• The array_shift () function removes the first element of an array.
• The array_push () function adds an element to the end of an array.
• The array_pop () function removes the last element of an array.

<?php
$arr=array('the lion king','car','a bug\'s life');
array_shift($arr);
array_pop($arr);
array_push($arr,'welcome');
array_unshift($arr,'hi');
print_r($arr);
?>
O/p
Array ( [0] => hi
[1] => car
[2] => welcome )
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -77-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

REMOVING DUPLICATE ARRAY ELEMENTS:


PHP lets you strip an array of duplicate values with its array_unique () function,
which accepts an array and returns a new array containing only unique values.
<?php
$duplicates=array('a','b','a','c','e','d','e');
$uniques=array_unique($duplicates);
print_r($uniques);
?>

O/p Array ( [0] => a


[1] => b
[3] => c
[4] => e
[5] => d )

RANDOMIZING AND REVERSING ARRAYS:


PHP’s shuffle () function re-arranges the elements of an array in random order,
while its array_reverse () function reverses the order of an array’s elements.
<?php
$rainbow=array('violet','indigo','blue','green','yellow','orange','red');
shuffle($rainbow);
print_r($rainbow);
$arr=array_reverse($rainbow);
print_r($arr);
?>
O/p
Array ( [0] => indigo [1] => violet [2] => green [3] => blue [4] => orange [5] =>
yellow [6] => red ) Array ( [0] => red [1] => yellow [2] => orange [3] => blue [4] => green
[5] => violet [6] => indigo )

SEARCHING ARRAYS:
The in_array () function looks through an array for a specified value and returns true
if found.
<?php
$rainbow=array('violet','indigo','blue','green','yellow','orange');
echo in_array('red',$rainbow)
?>

SORTING ARRAYS:
The first of these is the sort () function, which lets you sort numerically indexed
arrays alphabetically or numerically, from lowest to highest value.
• It’s better to use the ssort () function, which maintains the correlation between keys
and values while sorting.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -78-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

<?php
$profile=array("fname"=>"suresh",
"lname"=>"kumar",
"sex"=>"male",
"sector"=>"asset management");
asort($profile);
print_r($profile);
?>
o/p
Array ( [sector] => asset management
[lname] => kumar
[sex] => male
[fname] => suresh )

• Also related to associate arrays is the ksort () function, which uses keys instead of
values when performing the sorting.
<?php
$profile=array("fname"=>"suresh",
"lname"=>"kumar",
"sex"=>"male",
"sector"=>"asset management");
ksort($profile);
print_r($profile);
?>
o/p
Array ( [fname] => suresh [lname] => kumar [sector] => asset management [sex] =>
male )

MERGING ARRAYS:
PHP lets you merge one array into another with its array_merge () function, which
accepts one or more array variables.
<?php
$dark=array('black','brown','blue');
$light=array('while','silver','yellow');
$color=array_merge($dark,$light);
print_r($color);
?>
o/p
Array ( [0] => black [1] => brown [2] => blue [3] => while [4] => silver [5] => yellow
)
COMPARING ARRAYS:
PHP provides two functions to compare arrays:
• The array_intersect () function returns the values common to two arrays.
• The array_diff() function the values from the first array that don’t exist in the second.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -79-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

<?php
$orange=array('red','yellow');
$green=array('yello','blue');
$common=array_intersect($orange,$green);
print_r($common);
$unique=array_diff($orange,$green);
print_r($unique);
?>
o/p
Array ( [0] => red [1] => yellow )

Example Program : Checking Prime Numbers


Here’s the code (primes.php):
<html >
<head>
<title>Project 4-3: Prime Number Tester</title>
</head>
<body>
<h2>Project 4-3: Prime Number Tester</h2>
<?php
if (!isset($_POST['submit'])) {
?>
<form method="post" action="primes.php">
Enter a list of numbers, separated by commas: <br />
<input type="text" name="num" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
} else {
$numStr = $_POST['num'];
$numArr = explode(',', $_POST['num']);
$primes = array();
$primeFlag = 0;
foreach ($numArr as $n) {
$n = trim(abs($n));
for ($i=2; $i<$n; $i++) {
$primeFlag = 0;
if (($n%$i) == 0) {
break;
}
$primeFlag = 1;
}
if ($primeFlag == 1) {
array_push($primes, $n);
}
}

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -80-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

if (count($primes) > 0) {
$primes = array_unique($primes);
sort($primes);
echo 'The following numbers are prime: ' . implode($primes, ' ');
} else {
echo 'No prime numbers found';
}
}
?>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -81-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

UNIT – IV
PHP Advanced Concepts - Reading and Writing Files - Reading
Data from a File.

PHP ADVANCED CONCEPTS :


CREATING CLASSES:
PHP also allows you to group related functions together using a class.
Class are the fundamental construct behind object-oriented programming(OOP).
INTRODUCING CLASSES AND OBJECTS:
Variables within a class are called properties; functions are called methods. Classes serve as
templates for objects, which are specific instances of a class. To put this in more concrete
terms, consider an example: an automobile class that contain properties for color and make,
and methods for acceleration, braking, and turning.
DEFINING AND USING CLASSES:
A class definition begins with the class keyword, which is followed by the class name and a
pair of curly braces.
Object

Ford brake()
Class accelerate()
turn()
Object
Automobile brake()
Honda
accelerate()
brake() turn()
accelerate()
turn()
<?php
//class definition
class Automobile{
//properties
public $color;
public $make;
//methods
public function accelerate(){
echo ‘Accelerating…;
}
public function brake(){
echo ‘slowing down…’;
}

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -82-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

public function turn(){


Echo ‘turning…’;
}
}
?>
Once a class has been defined, objects can be created from the class with the new keyword.
<?php
//instantiate object
$car=new Automobile;
//set object properties
$car->color=’red’;
$car->make=’Ford Taurus’;
//invoke object methods
$car->accelerate();
$car->turn();
?>
Example Program : Encrypting and Decrypting Text
Take a look at the class definition (jumbler.php):
<?php
class Jumbler {
public $key;
public function setKey($key) {
$this->key = $key;
}
public function getKey() {
return $this->key;
}
public function encrypt($plain) {
for ($x=0; $x<strlen($plain); $x++) {
$cipher[] = ord($plain[$x]) + $this->getKey() + ($x * $this->getKey());
}
return implode('/', $cipher);
}
public function decrypt($cipher) {
$data = explode('/', $cipher);
$plain = '';
for ($x=0; $x<count($data); $x++) {
$plain .= chr($data[$x] - $this->getKey() - ($x * $this->getKey()));
}
return $plain;
}
}
?>
<html >
<head>
<title>Project 5-2: Encrypting Text</title>
</head>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -83-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

<body>
<h2>Project 5-2: Encrypting Text</h2>
<?php
if (!isset($_POST['submit'])) {
?>
<form method="post" action="jumbler.php">
Enter:
<input type="radio" name="type" value="P" checked>Plaintext</input>
<input type="radio" name="type" value="C">Ciphertext </input>
<br />
<textarea name="text" rows="6" cols="40" wrap="soft"></textarea>
<p>
Enter numeric key: <br />
<input type="text" name="key" size="6" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
} else {
$type = $_POST['type'];
$text = $_POST['text'];
$key = (int)$_POST['key'];
$j = new Jumbler;
$j->setKey($key);
if ($type == 'C') {
echo $j->decrypt($text);
} else {
echo $j->encrypt($text);
}
}
?>
</body>
</html>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -84-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

USING ADVANCED OOP CONCEPTS:

PHP’s object model also supports many more advanced features, giving developers a
great deal of power and flexibility in building OOP-driven applications.

USING CONSTRUCTORS AND DESTRUCTORS:


PHP makes it possible to automatically execute code when a new instance of a class is
created, using a special class method called a constructor. You can also run code when a class
instance ends using a so-called destructor. Constructors and destructors can be implemented
by defining functions named__construct() and __destruct() within the class, and placing
object (de)initialization code within them.
<?php
//define class
class Machine{
//constructor
function__construct() {
echo “Starting up…/n”;
}
//destructor
function__destruct() {
echo “Shutting down…/n”;
}
}
//create a object
//output: “Shutting down…”
unset($m);
?>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -85-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

→Extending Classes
For most developers, extensibility is the most powerful reason for using the OOP
paradigm. Put very simply, extensibility implies that a new class can be derived from an
existing one, inheriting all the properties and methods of the parent class and adding its own
new properties and methods as needed Thus, for example, a Human class could extend a
Mammal class, which is itself an extension of a Vertebrate class, with each new extension
adding its own features as well as inheriting the features of its parent. In PHP, extending a
class is as simple as attaching the extends keyword and the name of the class being extended
to a class definition, as in the following example:
<?php
class Mammal {
// class definition
}
class Human extends Mammal {
// class definition
}
?>
With such an extension, all the properties and methods of the parent class become
available to the child class and can be used within the class’ program logic. To illustrate,
consider the following listing:
<?php
// parent class definition
class Mammal {
public $age;
function __construct() {
echo 'Creating a new ' . get_class($this) . '...';
}
function setAge($age) {
$this->age = $age;
}
function getAge() {
return $this->age;
}
function grow() {
$this->age += 4;
}
}
// child class definition
class Human extends Mammal {
public $name;
function __construct() {
parent::__construct();
}
function setName($name) { $this->name = $name; }
function getName() {
return $this->name;
}
function grow() {
$this->age += 1;
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -86-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

echo 'Growing...';
}
}
?>

ADJUSTING VISIBILITY SETTINGS:


In the first of this chapter, you learned the difference between “local” and “global”
scope, and you saw how variables used inside a function or invisible to the main program.
<?php
//class tree
class mamma1{
public $name;
protected $age;
private $species;
}
class Human extends Mamma1 {
}
$mamma1=new Mamma1;
$mamma->name=’William’; //ok
$mamma->age=3; //fatal error
$mamma->species=’Whale’; //fatal error
$human=new Human;
$human->name=’Barry’;
$human->age=1;
$human->species=’Boy’;
?>

WORKING WITH FILES :

READING FILES:
PHP’s file manipulation API is extremely flexible; it lets you read files into a string or into an
array, from the local file system or a remote URL, by lines, bytes, or characters. The
following sections explain all these variants in greater detail.

READING LOCAL FILES:


The easiest way to read the content of a disk file in PHP is with the file_get_contents()
function.
Example 1:
<?php
//read file into string
$str=file_get_contents(‘example.txt’)or die(‘ERROR: Cannot find file’);
echo $str;
?>

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -87-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Example 2:
<?php
//read file into array
$arr=file(“example.txt’)or die(‘ERROR: Cannot find file’);
foreach ($arr as $line){
echo $line;
}
?>
READING REMOTE FILES:
Both file_get_contents() and file() also support reading data from URLs. Using either the
HTTP or FTP protocol. Here’s an example, which reads an HTML file off the Web into an
array:
<?php
//read file into array
$arr=file(‘http://www.google.com’)or die(“ERROR: Cannot find file ‘);
foreach ($arr as $line) {
echo $line;
} ?>

READING SPECIFIC SEGMENTS OF A FILE:


A final twist involves reading only a specific block of lines from a line—something that can
be accomplished with the combination of PHP’s fseek() and fgets() functions. Consider the
next example which sets up a user defined function named readBlock() and accepts three
arguments.
<?php
//function definition
//read a block of lines from file
function readBlock($file,$start=1,$lines=null) {
//open file
$fp=fopen($file,’r’)or die(‘ERROR: Cannot find file’);
$linesScanned = 1;
$linesRead = 0;
$out = '';
// loop until end of file
while (!feof($fp)) {
// get each line
$line = fgets($fp);
// if start position is reached
// append line to output variable
if ($linesScanned >= $start) {
$out .= $line;
$linesRead++;
// if max number of lines is defined and reached
// break out of loop
if (!is_null($linesRead) && $linesRead == ($lines)) {
break;

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -88-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

}
}
$linesScanned++;
}
return $out;
}
echo readBlock('example.txt', 3, 4);
?>

WRITING FILES:
The first is the file_put_contents() function, a cousin of the file_get_contents() function you
read about in the preceding section.
<?php
//write string to file
$data=”a fish \n out of \n water \n”;
file_put_contents(‘output.txt’,$data)
or die ERROR: Cannot find file’);
echo ‘Data written to the file’;
?>

→Reading and Writing Configuration Files

Here’s the code (configure.php):


<html>
<head>
<title>Project 6-1: Reading And Writing Configuration Files</title>
</head>
<body>
<h2>Project 6-1: Reading And Writing Configuration Files</h2>
<?php
// define configuration filename and path
$configFile = 'config.ini';
if (!isset($_POST['submit'])) {
// set up array with default parameters
$data = array();
$data['AdminEmailAddress'] = null;
$data['DefAuthor'] = null;
$data['NumPosts'] = null;
$data['NumComments'] = null;
$data['NotifyURL'] = null;
// read current configuration values
// use them to pre-fill the form
if (file_exists($configFile))
{
$lines = file($configFile);
foreach ($lines as $line) {
$arr = explode('=', $line);
$i = count($arr) - 1;
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -89-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

$data[$arr[0]] = $arr[$i];
}}
?>
<form method="post" action="configure.php">
Administrator email address: <br />
<input type="text" size="50" name="data[AdminEmailAddress]" value="<?php
echo $data['AdminEmailAddress']; ?>"/>
<p>
Default author name: <br />
<input type="text" name="data[DefAuthor]" value="<?php echo
$data['DefAuthor']; ?>"/>
<p>
Number of posts on index page: <br />
<input type="text" size="4" name="data[NumPosts]" value="<?php echo
$data['NumPosts']; ?>"/>
<p>
Number of anonymous comments: <br />
<input type="text" size="4" name="data[NumComments]" value="<?php echo
$data['NumComments']; ?>"/>
<p>
URL for automatic notification of new posts: <br />
<input type="text" size="50" name="data[NotifyURL]" value="<?php echo
$data['NotifyURL']; ?>"/>
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
} else {
$config = $_POST['data'];
if ((trim($config['NumPosts']) != '' && (int)$config['NumPosts'] <= 0) ||
(trim($config['NumComments']) != '' && (int)$config['NumComments'] <= 0)) {
die('ERROR: Please enter a valid number');
}
$fp = fopen($configFile, 'w+') or die('ERROR: Cannot open configuration
file for writing');
flock($fp, LOCK_EX) or die('ERROR: Cannot lock configuration file for
writing');
foreach ($config as $key => $value) {
if (trim($value) != '') {
fwrite($fp, "$key=$value\n") or die('ERROR: Cannot write [$key] to
configuration file');
}
}
flock($fp, LOCK_UN) or die ('ERROR: Cannot unlock file');
fclose($fp);
echo 'Configuration data successfully written to file.'; }
?>
</body>
</html>
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -90-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -91-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

UNIT – V
Managing Sessions and Using Session Variables – Destroying a Session-Storing
Data in Cookies-Setting Cookies.

SESSION VARIABLES:

Introduction
➢ Variables in PHP typically have a specific and limited scope—generally, a variable is
only available on the page on which it was declared. The prime exception to this rule
is when you declare a variable inside a function, it only works in that function.
➢ But what if you want access to the same variable across multiple pages in your
application? For instance, I’m a regular shopper on Amazon.com. If you are too, you
may have noticed that once you’re logged in, every page has your name on the top of
it.

➢ Presumably, there is a variable in a script somewhere called something like


$FirstName containing the value ‘Alan’. By now, you could probably easily write
such a script. Here’s a hint:
➢ But how does that value $FirstName pass from page to page as I wander about the
site? And how does the site keep track of hundreds of unique $FirstName variables
for all the unique customers who happen to be on the site at the same time? The
answer is session variables.

SESSIONS:

➢ A session variable is a special kind of variable that, once set, is available to all the
pages in an application for as long as the user has their browser open, or until the
session is explicitly terminated by the developer (you).
➢ The great thing about session variables is that PHP will magically keep track of which
particular session variable goes with each particular user. So while my Amazon.com
experience will always say “Alan’s Amazon”, yours will say something different
(unless your name also happens to be Alan, of course.) Sessions work by creating a
unique id (UID) for each visitor and storing variables based on this UID. The UID is
typically stored in a cookie.
➢ A Cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a
small piece of data sent from a website and stored in a user’ s browser while a
user is browsing a website.
➢ It doesn’t really matter how they work, the important thing is that they do work. And,
they are very cool.
➢ They open up a whole realm of possibilities for customizing your web application for
a specific customer.
➢ For example, in the case of Sam’s Used Cars, you could ask a customer their
preferred car color, make/model, features, etc.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -92-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ From that point on, you can customize the pages to reflect the customers’
preferences. For example, Hey look, this car has a sunroof! (And it’s red too!) It’s just
a sample app, so it’s OK to code annoying features to learn something valuable.
➢ Once a user closes their browser, the cookie will be erased and the session will end.
➢ So sessions are not a good place to store data you intend to keep for long. The right
place to store long-term data is in a database.
➢ Of course, sessions and databases can work together. For instance, you can store a
user’s preferences in a database, and retrieve them from the database when the user
“logs in” or types in their email address or does whatever it is that you coded for them
to identify themselves. Once the data is retrieved, assign the preferences to the session
variables and they will be available from then on.

STARTING A PHP SESSION:

➢ Before you can store user information in your PHP session, you must first start up the
session using the session_start() function.
➢ The session_start() function must appear BEFORE the <html> tag, or it won’t work.
<?php session_start( ); ?>
<html>
<body>
<p> Hello world</p>
</body>
</html>
➢ The code above will start the user’s session with the server and allow you to start
saving user information into session variables.

USING SESSION VARIABLES


➢ The correct way to store and retrieve session variables is to use the PHP $_SESSION
variable:

Store a variable:
<?php
session_start();
// store session data
$_SESSION[‘FirstName’]=’Naresh’;
?>
<html>
</html>

Retrieve a variable:

<?php
//retrieve session data
echo $_SESSION[‘FirstName’].” kumar ”;
?>

Output:
Nareshkumar

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -93-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Checking for a variable


➢ You can check to see if a session variable is available or not by using the isset()
function.
bool isset (mixed $var [,mixed $...])

Determines if a variable is set and is not NULL. You can unset a variable with
unset ( ).

Here’s an example:
<?php
session_start();
// store session data
if(isset($_SESSION[‘FirstName’]))
echo $_SESSION[‘FirstName’].”kumar”;
else
$_SESSION[‘views’]=1;
echo “Welcome to AAC”;
?>

DESTROYING A SESSION:
➢ If you wish to delete some session data, you can use the unset() function. If you want
to delete it all, use the session_destroy() function. The unset() function is used to
delete a specific session variable:

<?php
session_start();
if(isset($_SESSION[‘FirstName’]))
unset($_SESSION[‘FirstName’]));
?>

➢ You can also completely destroy all the session by calling the session_destroy()
function:
<?php
session_destory( );
?>
➢ Note: session_destroy() will reset your session and you will lose all your stored
session data. This is an easy way to implement a logout function.
➢ If you would like to learn more about Session Variables, I have a whole book on this
topic titled “The Joy of PHP: Deep Dive into Sessions”.

What is Cookies in PHP?


➢ Cookies in PHP play a crucial role in web development by enabling websites to store
and retrieve information on a user’s device. These small pieces of data, sent from a
web server and stored on the user’s browser, allow websites to remember user
preferences, track sessions, and maintain state information.
➢ In PHP, cookies can be customized to suit specific needs, thanks to key attributes that
provide control over their behaviour.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -94-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Key Cookie Attributes:

➢ Expires: This attribute sets the expiration date and time for a cookie. After this point, the
cookie becomes invalid and is automatically deleted by the browser. Cookies can be set to
expire at a specific date or when the browser session ends.
➢ Path: It defines the URL path for which the cookie is accessible. This attribute allows
you to specify a directory or a part of the website where the cookie should be available. It
helps in segmenting cookies for different purposes.
➢ Domain: The “domain” attribute specifies the domain (e.g., example.com) for which the
cookie is valid. This attribute is useful when you want a cookie to be accessible across
subdomains, enabling seamless user experiences.
➢ Secure: When this attribute is set to true, ensures that the cookie is only transmitted over
secure (HTTPS) connections. It enhances the security of sensitive information stored in
cookies.
➢ Understanding these key cookie attributes in PHP is essential for creating effective web
applications.
➢ By using these attributes strategically, you can tailor cookies to meet specific
requirements, whether it’s providing a personalized user experience, managing user sessions,
or enhancing security. To conduct such ideal practices in your PHP application you can also
consider requesting personalized assistance by hiring dedicated PHP developers.

Setting Cookies in PHP


➢ It is a fundamental aspect of web development, allowing you to store and retrieve
user-specific information and preferences.
➢ By using cookies, you can create a more personalized and user-friendly web
experience. In this section, we’ll delve into the practical steps of how to set cookies in
PHP.

1. Setting a Cookie in PHP


➢ To set a cookie in PHP, you’ll typically use the setcookie() function. This function
allows you to define the cookie’s name, value, and various attributes. Here’s a basic
example:
setcookie("cookie_name", "cookie_value");
2. Using the setcookie() Function
➢ The setcookie() function takes several parameters, including the cookie name, value,
expiration time, path, domain, and security settings. You can specify these parameters
to customize the behavior of your cookie.
3. Specifying Cookie Attributes
➢ As mentioned earlier, you can set attributes like “expires,” “path,” “domain,” and
“secure” to control how the cookie behaves. For example, you can set a cookie to
expire after a specific duration or ensure that it is only accessible on certain parts of
your website.
4. Examples of Setting Cookies
➢ Throughout your web development journey, you may need to set cookies for various
purposes, such as tracking user preferences, managing user sessions, or improving site
functionality.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -95-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

5. Practices for Setting Cookies


➢ To ensure a seamless and secure user experience, it’s essential to follow best practices
when setting cookies. This includes setting appropriate expiration times, restricting
cookies to specific paths, and using encryption for sensitive data.
➢ Setting cookies in PHP opens up a world of possibilities for enhancing your website’s
functionality and user experience. To assure the same and right code deployment you
can hand over your application to a PHP development company offering web
development services.
➢ Whether you’re customizing content, maintaining user sessions, or improving security
in your web development toolkit. In the following sections, we’ll explore examples
and best practices to guide you in effectively utilizing cookies in PHP.

STORING DATA IN COOKIES:

Steps for Setting Cookies in PHP


➢ It includes an essential mechanism that enables web developers to store and manage
user-specific data in a user’s browser, facilitating tailored browsing experiences and
session management.

1. Using setcookie() Function


➢ The setcookie() function in PHP facilitates the creation of cookies that are stored on a
user’s browser, enabling the preservation of specific information for subsequent page
visits.
➢ The setcookie() function takes parameters to define the cookie properties such as
name, value, expiration time, path, domain, and security.
Example:
setcookie("username", "JohnDoe", time() + 3600, "/");

➢ This example sets a cookie named “username” with the value “JohnDoe” that expires
in an hour, is accessible from the root directory, is associated with the domain
“example.com”, and is marked as secure.
2. Defining Cookie Name and Value
➢ Cookies in PHP require a name to identify the information and a value representing
the data to be stored.

• Choose a descriptive name for the cookie to identify its purpose.


• Assign the specific value to be stored in the cookie.
Example:
setcookie("user_id", "12345", time() + (86400 * 30), "/");

• This code sets a “user_id” cookie with the value “12345”, valid for 30 days and
accessible from the root directory.
• Defining the name and value of a cookie is fundamental to setting and identifying the
information stored within it.

3. Setting Expiration Time


The expiration time defines the duration until the cookie becomes invalid.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -96-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

• Determine the duration until the cookie expires using the time() function to specify
the expiration timestamp.
• Cookies can either persist until the browser session ends or have a specific expiration
time.
Example:
setcookie("session_token", "abc123", 0, "/");

• This code sets a “session_token” cookie that expires when the browser is closed.
Setting an expiration time allows for the management of how long the stored information
remains valid.

4. Setting Path and Domain (Optional)


The path and domain parameters define the scope and accessibility of the cookie.

• Specify the path and domain parameters to limit where the cookie is accessible.
Example:
setcookie("preferences", "settings", time() + 3600, "/settings/", ".example.com");

• The “preferences” cookie is set to expire in an hour, limited to the “/settings/”


directory and accessible across all subdomains of “example.com”.
• Setting the path and domain parameters defines the cookie’s scope, allowing selective
access across different parts of a website.

5. Ensuring Security (Optional)


Setting cookies for secure transmission over HTTPS connections helps enhance data security.

• For sensitive information, ensure the cookie is transmitted over secure connections by
setting the security parameter to true.
Example:
setcookie("secure_cookie", "12345", time() + 3600, "/", "", true);

➢ The “secure_cookie” is set to be transmitted securely, lasting for an hour and


available across the entire domain.
➢ Ensuring security when transmitting cookies helps protect sensitive data and user
privacy.
➢ Setting cookies in PHP empowers developers to create personalized and interactive
web experiences by storing and retrieving user-specific information across various
browsing sessions.
➢ Adjusting the parameters in the setcookie() function allows for tailored and secure
cookie management within web applications.

Retrieving Cookies in PHP


➢ Retrieving cookies in PHP is an essential aspect of managing user-specific
information within web applications.
➢ After cookies have been previously set and stored in a user’s browser, PHP enables
developers to access and retrieve these cookies to personalize experiences, maintain
sessions, and dynamically display content based on stored data.

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -97-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

Steps for Retrieving Cookies


➢ Retrieving cookies in PHP is an essential process to access and utilize stored user
data, allowing for personalized experiences and tailored functionalities within web
applications.

1. Using $_COOKIE Super global


➢ The ‘$_COOKIE’ super global array in PHP stores all cookies sent from the client’s
browser to the server. Accessing this array provides access to the stored cookie data.

Access the ‘$_COOKIE’ array to retrieve stored cookies.



Cookies are accessed using their unique names as keys within the ‘$_COOKIE’ array.

Example:
$username = $_COOKIE['username'];
➢ Utilizing the ‘$_COOKIE’ super global allows direct access to stored cookie
information, enabling developers to personalize content and manage user preferences
within their web applications effectively.

2. Accessing Specific Cookies


➢ Retrieving specific cookies involves referencing their unique names within the
‘$_COOKIE’ super global array, enabling the extraction of particular user data.

• Use the name of the desired cookie to access its stored value within ‘$_COOKIE’.
• Check for the existence of a specific cookie before retrieving its value.
Example:
if (isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
// Further operations using $username
}
➢ Accessing specific cookies allows developers to retrieve targeted user information,
facilitating the customization of web experiences and the implementation of
personalized features.
3. Checking Cookie Existence
➢ Prior to retrieving a specific cookie, it is advisable to verify its existence within the
‘$_COOKIE’ array to avoid potential errors.

•Use isset() to check if a particular cookie exists in the ‘$_COOKIE’ array.


•Validate the existence of cookies before accessing their values.
Example:
// Check if 'username' cookie exists
if (isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
echo "Welcome back, $username!";
// Further operations using $username
} else {
echo "Cookie 'username' not found or has expired.";
// Perform alternative actions or set the cookie if not present
}

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -98-


SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

➢ Verifying the existence of cookies helps in ensuring the availability of necessary user
data, preventing errors and enabling smooth operations while retrieving stored
information.

4. Processing Retrieved Cookie Data
➢ Upon retrieving the desired cookie, further processing of the obtained data is essential
for applying tailored functionalities within PHP applications.

• Utilize retrieved cookie data for customizing content, managing user preferences, or
implementing application-specific features.
• Process the retrieved cookie data as required by the application’s functionalities.
Example:
if (isset($_COOKIE['preferences'])) {
$preferences = json_decode($_COOKIE['preferences'], true);

// Process preferences (example: theme preferences)


if (isset($preferences['theme'])) {
$selectedTheme = $preferences['theme'];
// Apply the selected theme to the user interface
echo "Applying $selectedTheme theme.";
}
// Other preference handling...
} else {
echo "No stored preferences found.";
// Implement default preferences or guide the user to set preferences
}
➢ Processing retrieved cookie data allows developers to personalize the user experience,
manage preferences, and implement dynamic functionalities based on the stored user
data.
➢ Retrieving and processing cookies in PHP empowers developers to create
personalized and dynamic web applications, tailoring experiences and functionalities
to suit individual user preferences.
Updating and Deleting Cookies in PHP
➢ In web development, cookies play a crucial role in storing user-specific data and
preferences. However, there are scenarios where you might need to update or delete
cookies.
➢ Updating cookies allows you to modify their values while deleting cookies removes
them from the user’s browser. These actions are essential for maintaining data
accuracy and ensuring user privacy.

Steps for Updating and Deleting Cookies in PHP


➢ In PHP, cookies are utilized to store user-specific information. There are situations
where you may need to update or delete cookies to maintain accurate data or enhance
user privacy. These steps outline how to update and delete cookies while ensuring the
necessary existence check.

1. Updating Cookies
➢ Updating cookies is necessary when you need to change the values or attributes of a
cookie while keeping it active.
ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -99-
SBE-PHP PROGRAMMING M.NARESHKUMAR M.C.A.,M.PHIL.,B.ED.,

• To update a cookie, use the setcookie() function with the same name as the existing
cookie.
• Provide the new value and any modified attributes to overwrite the existing cookie.
Example:
// Updating the 'username' cookie with a new value
setcookie("username", "NewValue", time() + 3600, "/");
➢ Updating cookies ensures that they remain relevant and accurate, providing users with
the latest information.
2. Deleting Cookies
➢ Deleting cookies is important when you want to remove specific cookie data, either
because it’s no longer needed or for user privacy considerations.

•To delete a cookie, set its expiration time to a past date using the setcookie() function.
This causes the cookie to expire immediately.
• Make sure to set the path and domain attributes the same way they were set when the
cookie was originally created.
Example:
// Deleting the 'username' cookie
setcookie("username", "", time() - 3600, "/");
➢ Deleting cookies is crucial for user privacy and for removing obsolete or unwanted
data from the user’s browser.
3. Checking Cookie Existence (Before Updating or Deleting)
➢ Before updating or deleting a cookie, it’s wise to check if the cookie exists to avoid
errors.

• Use the isset() function to verify if a specific cookie is set before attempting to update
or delete it.
Example:
if (isset($_COOKIE['username']))
{
// Proceed with updating or deleting
}

ARIGNAR ANNA COLLEGE (ARTS AND SCIENCE)-KRISHNAGIRI -100-

You might also like