PHP Programming
PHP Programming
S Surya
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. 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.
PHP Introduction
The term PHP is an acronym for – Hypertext Preprocessor. PHP is a server-side scripting
language designed specifically for web development. It is an open-source which means it is free
to download and use. It is very simple to learn and use. The file extension of PHP is “.php”.
What is PHP?
PHP is a server-side scripting language created primarily for web development but it is also
used as a general-purpose programming language. Unlike client-side languages like JavaScript,
which are executed on the user’s browser, PHP scripts run on the server. The results are then
sent to the client’s web browser as plain HTML.
History of PHP
PHP was introduced by Rasmus Lerdorf in 1994, the first version and participated in the later
versions. It is an interpreted language and it does not require a compiler. The language quickly
evolved and was given the name “PHP,” which initially named was “Personal Home Page.”
PHP 3 (1998): The first version considered suitable for widespread use.
PHP 4 (2000): Improved performance and the introduction of the Zend Engine.
PHP 5 (2004): Added object-oriented programming features.
PHP 7 (2015): Significant performance improvements and reduced memory usage.
1
Dr.S Surya
Syntax
<?php
// PHP code goes here
?>
2
Dr.S Surya
<!DOCTYPE html>
<html>
<head>
<title>PHP Hello World</title>
</head>
<body>
<?php echo "Hello, World! This is PHP code";?>
</body>
</html>
Output:
3
Dr.S Surya
Web Applications: PHP is used for creating feature-rich web applications such as social
media platforms, forums, and customer relationship management (CRM) systems.
API Development: PHP can be used to create APIs for web and mobile applications.
Why should we use PHP?
PHP can actually do anything related to server-side scripting or more popularly known
as the backend of a website. For example, PHP can receive data from forms, generate dynamic
page content, can work with databases, create sessions, send and receive cookies, send emails,
etc. There are also many hash functions available in PHP to encrypt users’ data which makes
PHP secure and reliable to be used as a server-side scripting language. So these are some of
PHP’s abilities that make it suitable to be used as a server-side scripting language. You will get to
know more of these abilities in further tutorials.
Even if the above abilities do not convince you of PHP, there are some more features of PHP. PHP
can run on all major operating systems like Windows, Linux, Unix, Mac OS X, etc. Almost all of
the major servers available today like Apache supports PHP. PHP allows using a wide range of
databases.
Advantages of PHP
Open Source: PHP is an open-source language, meaning it is freely available for anyone
to use and distribute. This openness has fostered a large and active community of
developers who continuously contribute to its growth, improvement, and feature
development.
Easy to Learn: The syntax of PHP is quite similar to C and other programming
languages. This makes PHP relatively easy to learn, especially for developers who
already have some programming experience. Beginners find it approachable due to its
straightforward syntax and extensive online resources.
Web Integration: PHP is designed specifically for web development and is embedded
within HTML. It seamlessly integrates with various web technologies, facilitating the
creation of dynamic and interactive web pages.
Database Support: PHP has excellent support for various databases, including MySQL,
PostgreSQL, SQLite, and more. This makes it easy to connect and interact with databases,
a crucial aspect of many web applications.
Cross-Platform Compatibility: PHP is platform-independent and runs on various
operating systems, including Windows, Linux, macOS, and others. This ensures
compatibility across different environments.
Large Community and Documentation: PHP has a vast and active community of
developers. The abundance of online resources, tutorials, and documentation makes it
easier for developers to find solutions and seek help when needed.
Frameworks and CMS: There are popular PHP frameworks like Laravel, Symfony, and
CodeIgniter, which provide pre-built modules and features, aiding in rapid development.
Additionally, PHP supports widely used content management systems (CMS) like
WordPress and Joomla.
4
Dr.S Surya
Server-Side Scripting: PHP scripts are executed on the server, reducing the load on the
client’s side. This server-side scripting capability is crucial for generating dynamic
content and performing server-related tasks.
Community Support: The PHP community actively contributes to the language’s
development, ensuring regular updates, security patches, and improvements.
Disadvantages of PHP
Inconsistency: PHP has been criticized for inconsistencies in function names and
parameter orders. This can lead to confusion for developers, especially when working
with a mix of older and newer functions.
Security Concerns: If not handled properly, PHP code may be susceptible to security
vulnerabilities, such as SQL injection and cross-site scripting (XSS). Developers need to
be cautious and follow best practices to secure PHP applications.
Performance: While PHP performs well for many web applications, it may not be as fast
as some compiled languages like C or Java. However, advancements and optimizations in
recent versions have improved performance.
Lack of Modern Features: Compared to newer languages, PHP may lack some modern
language features. However, recent versions of PHP have introduced improvements and
features to address this concern.
Scalability Challenges: PHP can face challenges when it comes to scaling large and
complex applications. Developers may need to adopt additional tools or frameworks to
address scalability issues.
Not Suitable for Large-Scale Applications: While PHP is suitable for small to medium-
sized projects, it might not be the best choice for extremely large and complex
applications where more structured languages might be preferred.
Limited Object-Oriented Programming (OOP) Support: Although PHP supports OOP,
its implementation has been criticized for not being as robust as in some other
languages. However, recent versions have introduced improvements to enhance OOP
capabilities.
PHP plays a central role in the development of dynamic websites. These are
websites that interact with users, handle forms, databases, authentication, and more.
If you're learning PHP for web development, here's an overview of how PHP is
commonly used to build websites.
A dynamic website is one whose content can change or update based on user
interactions or data retrieved from databases. PHP, being a server-side language, is
widely used for these kinds of websites.
5
Dr.S Surya
User dashboards
Content Management Systems (CMS)
E-commerce platforms
Social networks
Static websites, on the other hand, contain fixed content and don't change based
on user input. Static sites are usually written in HTML, CSS, and JavaScript, but PHP
is not typically used on these sites.
PHP is a server-side scripting language, which means it runs on the web server
rather than in the user's browser. This allows PHP to generate dynamic content,
interact with databases, and manage session states for each user.
Server-side processing: The browser sends requests to the server, and PHP
processes these requests to return HTML, data, or any other content to the client.
Database interaction: PHP is commonly used in combination with MySQL (or
other databases) to store and retrieve data, such as user accounts, posts, product
listings, and more.
Session management: PHP can maintain user sessions, helping to manage
logins, shopping carts, and personalized content.
1. User Requests a Page: The user types a URL in the browser or clicks a link.
2. Request Sent to Web Server: The request is sent to the server where the PHP
file is located.
3. PHP Script Executes: The PHP code runs on the server. It may:
o Retrieve data from a database.
o Process form input.
o Generate dynamic content based on conditions or user actions.
4. Output Sent to Browser: The PHP script sends HTML, CSS, and JavaScript back
to the user’s browser, which renders the page.
A PHP file typically ends with the .php extension and can contain both PHP code
and HTML. This allows dynamic content to be embedded directly within static HTML
pages.
6
Dr.S Surya
<?php
// Example of connecting to a MySQL database in PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
3. Session Management
PHP can manage user sessions, which is useful for login systems and other user-
specific interactions.
<?php
// Start a session
session_start();
7
Dr.S Surya
PHP handles database interactions (posts, pages, media) and the logic behind the
content.
Templates and themes are used to display the content dynamically.
5. E-commerce Websites
PHP is often used in building e-commerce websites (like shopping carts, product catalogs, order
management, etc.).
Shopping carts: PHP stores temporary data (cart items) in sessions or databases.
Product listings: PHP retrieves product data from a database and displays it dynamically
on the page.
7. Security Considerations
When developing websites with PHP, security is a key concern. Some common security issues
include:
SQL Injection: Prevent this by using prepared statements or ORM (Object-Relational
Mapping) tools.
Cross-Site Scripting (XSS): Sanitize and escape user input (e.g., using
htmlspecialchars()).
Cross-Site Request Forgery (CSRF): Use tokens to protect forms from CSRF attacks.
Password Storage: Use PHP's password_hash() and password_verify() functions to
securely hash and verify user passwords.
Conclusion
PHP is essential for building dynamic websites, allowing for interactions with users, databases,
and content management systems. Its ability to integrate with HTML, handle form data, manage
sessions, and connect to databases makes it one of the most popular choices for web
development. Understanding how PHP interacts with the server, client, and database will help
you build powerful and interactive websites.
A dynamic website is a type of website that generates content on the fly, based on user
interactions, database queries, or other conditions. Unlike static websites, which display fixed
8
Dr.S Surya
content that doesn't change unless manually edited, dynamic websites can update and modify
their content in real time.
PHP is one of the most commonly used programming languages for creating dynamic websites.
It allows web developers to build server-side logic that can interact with databases, manage user
input, and personalize content for visitors.
In a dynamic website, PHP handles the server-side processes such as:
Retrieving data from a database
Processing form submissions
Managing user sessions (logins, shopping carts, etc.)
Generating dynamic content (e.g., blog posts, product listings, user dashboards)
PHP (Hypertext Preprocessor) is a server-side scripting language, meaning that PHP code runs
on the web server and generates HTML, CSS, or JavaScript which is then sent to the user's
browser. PHP is often used for tasks like:
Processing forms: When a user submits a form (e.g., contact form, user registration
form), PHP processes the data, saves it in a database, and sends a response back to the
user.
Handling databases: PHP communicates with databases like MySQL or PostgreSQL to
retrieve, store, and update data (e.g., user accounts, blog posts, product listings).
Session and cookie management: PHP helps track users across different pages,
especially when managing user logins or shopping carts.
Generating dynamic HTML: Based on the user’s actions, PHP can generate and serve
different content dynamically, such as user profiles, blog articles, and product catalogs.
1. User Request:
o A user visits the website and makes a request (e.g., clicks a link, submits a form).
2. PHP Server-Side Logic:
o The request is processed by PHP code running on the server. This might include:
Checking if a user is logged in.
9
Dr.S Surya
SQL
CREATE DATABASE my_database;
USE my_database;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL
);
-- Insert a test user
INSERT INTO users (username, password) VALUES ('john', 'password123');
10
Dr.S Surya
PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
session_start();
$_SESSION['username'] = $user;
header("Location: profile.php"); // Redirect to the profile page
} else {
echo "Invalid username or password!";
}
$conn->close();
?>
if (!isset($_SESSION['username'])) {
header("Location: login.php"); // Redirect to login page if not logged in
11
Dr.S Surya
exit();
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "User ID: " . $row["id"] . "<br>";
echo "Username: " . $row["username"] . "<br>";
}
} else {
echo "No user found!";
}
$conn->close();
?>
12
Dr.S Surya
In these websites the content can be quickly changed on the user’s computer without
new page request to the web browser.
In these websites the owner have the ability to simply update and add new content to
the site.
These websites are featured with content management system, e-commerce system and
intranet or extranet facilities.
Most of the dynamic web content, is assembled on the web using server-scripting
languages.
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
13
Dr.S Surya
Conclusion
PHP is a powerful server-side scripting language for creating dynamic websites. It interacts with
databases, processes user input, and generates dynamic content, making it essential for building
interactive, data-driven websites such as social networks, e-commerce sites, blogs, and more.
With PHP, developers can create flexible and responsive web applications that adapt to user
needs and interactions in real time.
Scope of PHP
PHP (Hypertext Preprocessor) is one of the most widely-used server-side scripting languages
for web development. Since its release in 1995, PHP has become a foundational technology for
building dynamic and interactive websites. Despite the rise of various other programming
languages and frameworks, PHP continues to maintain its dominance, especially in web
development. This is due to its versatility, extensive support, and strong community backing.
Let’s explore the scope of PHP in various areas of web development and beyond:
1. Web Development
2. Database-Driven Applications
3. Server-Side Scripting
4. Web APIs and Web Services
5. Frameworks and Modern Web Development
6. Command-Line Scripting and Automation
7. Security in PHP
8. Mobile Development and PHP
9. Cloud Integration and Microservices
1. Web Development
PHP is primarily used for building dynamic, data-driven websites and web applications. Its
scope in web development includes:
a. Content Management Systems (CMS)
PHP is the backbone of many popular content management systems. These platforms allow
users to create, edit, and manage content on websites without needing to know how to code.
Some of the most famous CMS platforms are:
WordPress: The most widely used CMS, built with PHP, powers over 40% of websites on
the internet. WordPress allows users to create blogs, portfolios, e-commerce sites, and
more, with minimal technical knowledge.
Joomla!: Another PHP-based CMS that is used for more complex websites, including
corporate websites, community platforms, and online magazines.
14
Dr.S Surya
Drupal: Known for its flexibility and scalability, Drupal is often used in enterprise-level
websites and applications. PHP provides the framework for content management and
customizations.
b. E-commerce Platforms
PHP is widely used to build e-commerce websites, where PHP interacts with databases to
manage products, user data, and transactions. Well-known PHP-based e-commerce platforms
include:
Magento: A highly customizable, open-source e-commerce platform that uses PHP for
backend development.
WooCommerce: A WordPress plugin for e-commerce that extends the platform’s
functionality to allow users to build online stores with ease.
PrestaShop: Another PHP-based e-commerce platform for building online shops.
PHP enables developers to handle product catalogs, payment systems, customer accounts, and
order management in e-commerce websites.
c. Social Media and Networking Websites
PHP is also used for building social networking sites, where user interaction is key. Popular PHP-
based platforms include:
Facebook (initially): Although Facebook has moved to other technologies over time, it
started as a PHP-based project.
BuddyPress: A plugin for WordPress that allows developers to create social networks.
PHP's ability to handle large-scale applications and manage real-time user data makes it well-
suited for developing interactive social networking platforms.
2. Database-Driven Applications
One of PHP’s core strengths is its ability to interact seamlessly with databases. Most dynamic
websites need to retrieve, store, and modify data based on user input or other conditions, and
PHP plays a key role in this.
a. MySQL and PHP
PHP pairs with MySQL (or other relational databases) to build database-driven applications.
Some key features include:
User Authentication: Storing and verifying user credentials in a secure way.
Data Management: Fetching, displaying, and modifying data such as posts, comments,
orders, products, and more.
CRUD Operations: PHP simplifies the process of creating, reading, updating, and
deleting data in a database.
15
Dr.S Surya
b. NoSQL Databases
While PHP is most commonly associated with MySQL, it also works well with NoSQL databases
like MongoDB. These databases store data in formats other than traditional tables, and PHP can
interact with them to build flexible, scalable applications.
3. Server-Side Scripting
PHP is primarily known as a server-side scripting language, meaning that it runs on the web
server to generate HTML, handle form submissions, manage user sessions, and perform other
tasks that cannot be done on the client side (in the user's browser).
Handling Forms: PHP processes user inputs from forms (e.g., contact forms,
registration forms) and performs tasks like validation, storing the data in a database, or
sending email notifications.
Session Management: PHP can handle user sessions and cookies, allowing for features
like user logins, shopping carts, and personalized experiences.
File Management: PHP can create, read, write, and delete files on the server, which is
useful for tasks like file uploads, logs, or generating downloadable reports.
16
Dr.S Surya
Symfony: A flexible and robust framework often used for large-scale applications. It's
used in enterprise-level projects and is also the foundation for other platforms like
Drupal and Magento.
CodeIgniter: A lightweight and straightforward framework that’s perfect for developers
who need to build small to medium-sized applications quickly.
Yii: A high-performance framework designed for building fast and secure applications.
These frameworks come with built-in tools for authentication, routing, database access,
templating, and testing, making PHP development more efficient.
7. Security in PHP
Security is a critical aspect of PHP's scope. With PHP, developers can build secure applications
by incorporating features like:
Password Hashing: PHP provides functions like password_hash() and
password_verify() to securely store and check user passwords.
Input Validation: Preventing attacks like SQL injection and XSS (Cross-Site Scripting)
through proper validation and sanitization of user inputs.
CSRF Protection: Using tokens to protect against Cross-Site Request Forgery.
SSL/TLS: PHP can handle secure HTTP connections (HTTPS), ensuring data transmitted
between the server and the client is encrypted.
17
Dr.S Surya
Conclusion
The scope of PHP is vast and continues to evolve. From building dynamic websites and
applications to interacting with databases, handling server-side logic, and integrating with APIs,
PHP remains one of the most versatile and widely-used languages in web development. Its large
ecosystem of frameworks, libraries, and CMS platforms ensures that PHP will remain a key
player in web development for the foreseeable future. Whether you're building a simple blog or
a complex enterprise application, PHP offers the tools and flexibility to build robust, dynamic
websites.
XAMPP and WAMP Installation
Both XAMPP and WAMP are popular software packages that allow you to set up a local web
server on your machine to develop and test PHP-based websites. They both include Apache (a
web server), MySQL (a database server), and PHP (a scripting language). The main difference
between XAMPP and WAMP is the platforms they support and their ease of use.
XAMPP is a cross-platform package (available for Windows, Linux, and macOS).
WAMP is specifically designed for Windows.
Let’s go over the installation steps for both XAMPP and WAMP.
18
Dr.S Surya
6. Complete Installation:
o Once installed, you’ll see a success message. Click Finish to complete the
installation.
Step 3: Start XAMPP
Open the XAMPP Control Panel (located in the XAMPP installation directory, e.g., C:\
xampp\xampp-control.exe).
In the control panel, start the following services:
o Apache (web server)
Click on Start next to Apache and MySQL. If they turn green, it means they are running
successfully.
Step 4: Test the XAMPP Setup
Open your web browser and type http://localhost/ in the address bar.
If you see the XAMPP welcome page, your server is successfully installed and running.
Step 5: Using phpMyAdmin (Database Management)
To manage MySQL databases, open http://localhost/phpmyadmin/ in your browser.
You can create, modify, and delete databases here.
19
Dr.S Surya
6. Complete Installation:
o Once the installation is complete, click Finish.
20
Dr.S Surya
o Search for Listen 80 and change it to another port, such as Listen 8080.
o Save the file and restart Apache from the XAMPP control panel.
Conclusion
Both XAMPP and WAMP are excellent tools for setting up a local server for PHP development.
The installation process is simple, and both packages come with useful tools like phpMyAdmin
for database management and a control panel for managing Apache and MySQL services.
XAMPP is suitable for developers working across multiple platforms (Windows, macOS,
and Linux).
WAMP is designed specifically for Windows users and offers a user-friendly interface for
web development.
Once installed, you can start building, testing, and deploying PHP-based websites locally on your
machine before pushing them to a live server.
21
Dr.S Surya
Two-mark questions:
1.What is PHP?
The term PHP is an acronym for – Hypertext Preprocessor. PHP is a server-side scripting
language designed specifically for web development. It is an open-source which means it is free
to download and use. It is very simple to learn and use. The file extension of PHP is “.php”.
2.Explain PHP syntax.
Syntax
<?php
// PHP code goes here
?>
22
Dr.S Surya
The full form of XAMPP is Cross-Platform (X), Apache (A), MariaDB(M), PHP (P), and
Perl (P).
It allows them to test and debug their websites or applications in a controlled setting
before deploying them to the public. One of the most popular and user-friendly local
server solutions is XAMPP.
WAMP is an abbreviation for Windows, Apache, MySQL, and PHP. This is a software stack
that acts as a virtual server on a local computer.
WAMP for internal testing and web development. You can also use it for live websites.
The letter A in WAMP is for Apache or Apache web server. You use Apache as the tool
that's going to make it possible to run websites on Windows.
Five-mark questions
Ten-mark Questions
23