23ucas04 - PHP Notes
23ucas04 - PHP Notes
M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
ASST.PROFESSOR
KRISHNAGIRI
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.
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.
UNIT - I
Introduction to PHP – Basic Knowledge of websites – Introduction of Dynamic
Website - Introduction to PHP - Scope of PHP-XAMPP and WAMP Installation.
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.
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:
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.
➢ 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
➢ 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.
➢ 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
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.
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.
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.
XAMPP
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”
➢ 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”
➢ 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”
➢ Step 8
The “Install window” appears, click “Install” and wait until the installation is complete.
➢ Step 9
Then, click “Next” on the information screen.
That’s it. The WAMP is now located in the selected location that you have selected.
➢ 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.
➢ 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).
✓ 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.
➢ 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.)
➢ 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.
➢ 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.
➢ 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.,
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.
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
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.
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.
➢ 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
➢ 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 */
?>
➢ 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.
➢ 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
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:
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.
<?php
$name = "Softmastx";
echo "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";
?>
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!
<?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>";
}
?>
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
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
➢ 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”;
?>
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);
?>
● 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.
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.,
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);
?>
Operator Description
+= Add and assign
-= Subtract and assign
*= Multiplication and assign
/= Divide and assign quotient
%= Divide and assign modulus
.= Concatenate and assign
(strings only)
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;
?>
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:
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.
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.,
➢ 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:
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).
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.
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.
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
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);
?>
<?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>
Output:
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.
// 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.
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
<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>
'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';
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.
$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
• 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.
PHP has numerous built-in- array manipulation functions, supporting operations ranging
from array search and comparison to sorting and conversion operations
• 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”.
<?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.
• 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
<?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.,
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.
<?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 )
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>
UNIT – IV
PHP Advanced Concepts - Reading and Writing Files - Reading
Data from a File.
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…’;
}
<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>
PHP’s object model also supports many more advanced features, giving developers a
great deal of power and flexibility in building OOP-driven applications.
→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...';
}
}
?>
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.
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;
} ?>
}
}
$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’;
?>
$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.,
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.
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.
➢ 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.
➢ 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.
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
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”.
➢ 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.
➢ 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.
• 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.
• 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.
• Specify the path and domain parameters to limit where the cookie is accessible.
Example:
setcookie("preferences", "settings", time() + 3600, "/settings/", ".example.com");
• 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);
• 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.
➢ 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);
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
}