UNIT-1 PHP
UNIT-1 PHP
INTRODUCTION TO PHP
WHAT IS PHP?
• What is PHP?
• PHP (PHP: Hypertext Preprocessor) is an open-source, server-side scripting language widely used for
web development. It allows developers to create dynamic and interactive web pages by embedding PHP
code within HTML. The PHP interpreter processes the PHP scripts on the server and generates the final
HTML content, which is then sent to the user's browser. This ensures that the underlying PHP code
remains hidden from the user.
• Key Features of PHP:
• Server-Side Scripting
• PHP is a server-side scripting language, meaning it executes code on the web server before sending the
output (usually HTML) to the user's browser.
• Unlike client-side languages like JavaScript, which run in the browser, PHP runs on the server, making it
useful for handling tasks such as:
• Processing form submissions
• Handling file uploads
• Managing user sessions
• Interacting with databases
• Cross-Platform Compatibility
• PHP is a platform-independent language, meaning it can run on multiple operating systems, including:
• Windows
• Linux
• macOS
• It is also compatible with different web servers like Apache, Nginx, and IIS.
• This flexibility allows developers to write PHP code once and deploy it on various environments without
major modifications.
• . Database Integration
• PHP has built-in support for numerous databases, making it easy to develop data-driven web
applications.
• It supports popular databases such as:
• MySQL (commonly used for web applications)
• PostgreSQL (used for high-performance applications)
• Oracle, SQLite, MongoDB, and more.
• PHP provides APIs like PDO (PHP Data Objects) and MySQLi (MySQL Improved) for secure database
interactions.
• Easy to Learn
• PHP has a simple and easy-to-understand syntax, making it a great choice for beginners.
• If a developer is already familiar with languages like C, Java, or JavaScript, learning PHP becomes even
easier because of its similar structure.
• Unlike other languages that require complex configurations, PHP can be written directly into an HTML
file and executed with minimal setup.
Rich Functionality
•PHP includes a wide range of built-in functions to handle various tasks, reducing the need for additional code.
•Some common functionalities include:
•String manipulation – Concatenation, trimming, substring search, etc.
•File handling – Reading, writing, uploading, and deleting files.
•Session & cookie management – Tracking user sessions and preferences.
•Image processing – Using the GD library to create and modify images dynamically.
•Email handling – Sending emails with attachments using mail() or third-party libraries.
•These built-in features allow developers to build powerful applications efficiently
• Comprehensive Documentation & Community Support
• PHP has one of the largest open-source developer communities.
• The official PHP documentation (php.net) provides detailed explanations and examples for every
function.
• Developers can find additional help through:
• Online forums (Stack Overflow, PHP Freaks, Dev.to)
• Video tutorials (YouTube, Udemy, Coursera)
• Open-source projects (GitHub, CodeIgniter, Laravel repositories)
• This strong support system makes it easier to learn, troubleshoot, and improve PHP applications.
• Security Features
• PHP includes built-in security features to help protect web applications from attacks, such as:
• SQL Injection Prevention – Using prepared statements to prevent malicious database queries.
• Cross-Site Scripting (XSS) Protection – Filtering and sanitizing user inputs to block script injections.
• Cross-Site Request Forgery (CSRF) Protection – Using tokens to prevent unauthorized actions from
malicious sources.
• Data encryption :function like hash() ,openssl_encrypt() are used
• Availability of Frameworks & CMS
• PHP has a rich ecosystem of frameworks and Content Management Systems (CMS) that speed up
development.
• Popular PHP Frameworks
• Laravel – Offers elegant syntax, database migrations, authentication, and MVC architecture.
• CodeIgniter – Lightweight framework for fast development with minimal setup.
• Symfony – Enterprise-level framework with reusable components.
• Popular PHP CMS:
• WordPress – Most widely used CMS for building blogs and websites without coding.
• Drupal – Used for complex, content-heavy websites with advanced customization.
• Joomla – A flexible CMS for eCommerce and social networking sites.
HISTORY OF PHP
• PHP was originally developed by Rasmus Lerdorf in 1994 as a set of Perl scripts to track visitors to his
personal website. He later rewrote it in C and released it as "Personal Home Page Tools" (PHP Tools).
• Evolution of PHP Versions
1. PHP 1.0 (1995): Released as "Personal Home Page/Forms Interpreter (PHP/FI)"; it provided basic form
handling and database integration.
2. PHP 3 (1998): The language was rewritten, introducing a more structured syntax and supporting object-
oriented programming.
• PHP 4 (2000): Added the Zend Engine, improving performance and extensibility.
• PHP 5 (2004): Introduced better object-oriented programming (OOP) and MySQLi for enhanced
database support.
• PHP 7 (2015): Brought major performance improvements, better error handling, and a lower memory
footprint.
• PHP 8 (2020 - Present): Introduced Just-In-Time (JIT) compilation, union types, and improved error
handling for enhanced speed and efficiency.
• A PHP file is a server-side script that has a .php extension and contains a combination of text, HTML,
and PHP scripts. When a client (user) requests a PHP file via a web browser, the web server processes
the PHP code and generates the final HTML output, which is sent to the user’s browser.
• Components of a PHP File
• A PHP file typically contains three main components:
• 1. Text (Static Content)
• PHP files can include plain text that is displayed exactly as written.
• This text is treated as static content, meaning it remains unchanged unless modified in the PHP script.
• HTML Tags (For Structuring Web Pages)
• PHP files often contain HTML to format and display content.
• PHP and HTML can be mixed within the same file.
• HTML provides structure, while PHP adds dynamic content.
<!DOCTYPE html>
<html>
<head>
<title>My PHP Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a static paragraph inside an HTML page.</p> </body> </html>
PHP Scripts (Dynamic Content & Server-Side Processing)
The real power of PHP comes from embedding PHP scripts inside HTML. PHP code is enclosed within special PHP
tags:
<?php
// PHP code goes here
?>
• PHP can perform various tasks, such as:
Handling user input
Performing calculations
Accessing databases
Sending emails
Managing sessions and cookies
INSTALLATION AND CONFIGURATION OF
PHP
• Comments are used by developers to explain the code, making it easier to understand and
maintain. They are not executed by the PHP engine. There are two main types:
• Single-Line Comments
• Syntax:
Single-line comments start with // and continue until the end of that line.
<?php
// This is a single-line comment explaining that we are initializing a variable $x = 5; // This comment
explains that $x is set to 5
?>
Use single-line comments for short explanations or notes about a particular line of code.
Multi-Line Comments:
• Syntax:
Multi-line comments begin with /* and end with */ They can span several lines.
• <?php
• /* * This is a multi-line comment.
• * It is useful for providing detailed explanations
• * that span multiple lines.
• */ $x = 5;
• ?>
• Usage:
Multi-line comments are ideal for longer descriptions or when you need to temporarily
disable a block of code during testing.
WHITESPACE
Whitespace in PHP refers to any space, tab, or newline (line break) characters inserted into your
code to improve its readability and organization. Although the PHP interpreter largely ignores
these characters during execution, thoughtful use of whitespace has several benefits for
developers and teams. Let’s break down the key concepts:
• What is Whitespace in PHP?
• Definition:
Whitespace includes spaces, tabs, and newlines inserted in your code.
• Interpreter Behavior:
PHP does not treat whitespace as significant in most cases. This means:
• $a=5 ;is functionally the same as $a = 5;
• Benefits of Proper Whitespace Usage:
• Readability:
Properly spaced code is easier for developers to read and understand. Consistent spacing around
operators, keywords, and punctuation makes it clear where one element ends and another begins.
• Maintainability:
Clear indentation and separation of code blocks make it easier to locate errors or update parts of
the code without confusion. It also facilitates collaboration among team members.
• Code Aesthetics:
Consistent formatting reflects professionalism. Cleanly formatted code is not only easier to debug
and maintain but also creates a better overall impression for anyone reviewing or using the code.
EXAMPLE 1: ASSIGNMENT OPERATIONS AND
VARIABLE DECLARATIONS
• <?php
• // Without proper whitespace - harder to read:
• $a=5;
• echo"Hello World!";
• PHP is a dynamically typed language, meaning that variables do not need an explicit type
declaration; PHP determines the data type at runtime based on the assigned value.
• PHP has several primitive, composite, and special data types:
Primitive Data Types:
• These are fundamental types that hold single values.
Integer
• Whole numbers without a decimal part.
• Can be represented in decimal (base 10), hexadecimal (base 16), octal (base 8), and binary
(base 2).
• Eg:
$decNumber = 1234; // Decimal number
$hexNumber = 0x1A; // Hexadecimal (26 in decimal)
$octNumber = 01234; // Octal (668 in decimal)
$binNumber = 0b1010; // Binary (10 in decimal)
Float (Double)
• Numbers with a decimal point or in exponential notation.
Ex:
$floatNumber = 1.234; // Floating-point number
$expNumber = 1.2e3; // Exponential notation (1.2 × 10^3 = 1200)
String
• A sequence of characters enclosed in single ('') or double ("") quotes.
Ex:
• $singleQuoteString = 'Hello, world!';
• $doubleQuoteString = "Hello, world!";
Boolean
• Represents true or false values.
$isTrue = true;
$isFalse = false;
• Composite Data Types
• These hold multiple values.
Array
• Stores multiple values in a single variable.
$numArray = array(1, 2, 3, 4, 5);
$assocArray = array("name" => "John", "age" => 25);
• PHP 5.4, a shorter syntax can be used:
$numArray = [1, 2, 3, 4, 5];
Object
• PHP supports Object-Oriented Programming (OOP).
• Objects are instances of user-defined classes.
class Car {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
}
$myCar = new Car("Toyota");
echo $myCar->brand; // Output: Toyota
Special Data Types
• These have unique purposes.
NULL
• Represents a variable with no value or an explicitly NULL value.
Ex . $nullVar = NULL;
Resource
• Holds references to external resources such as database connections, file handles, and streams.
• Example:
$fileHandle = fopen("text.txt", "r"); // Opens a file for reading
PHP KEYWORDS
• Keywords are reserved words in PHP that serve specific functions and cannot be used as
variable names, function names, or class names.
• Variable Declaration
In PHP 4 and earlier, “var” was used to declare class properties.
In PHP 5 and later “public”, “protected” and “private” are used
class Example {
public $name; // Public property
private $age; // Private property
protected $email; // Protected property
}
Control Structures
• These keywords handle conditional logic and flow control
Keyword Description
“if”, “else”, “elseif”, “switch”, “case”, ”default” Used for conditional statements.
“Break”, “continue” Used to exit or skip loop iterations.
• $age = 20;
• if ($age >= 18) {
• echo "Adult";
• } else {
• echo "Minor";
• }
Loops
• These keywords execute code multiple times.
Keyword: description
“For”, “foreach”, “while”, “whileloop” Used for looping through data.
Types of Loops in PHP:
• for – Executes a block of code a specific number of times.
• while – Repeats as long as a condition is true.
• do...while – Executes at least once, then continues based on a condition.
• foreach – Iterates over arrays.
Loop Control Statements
• break – Exits a loop immediately.
• continue – Skips the rest of the current iteration and moves to the next cycle.
FUNCTIONS IN PHP
• PHP is an object-oriented programming (OOP) language that supports the creation and
manipulation of classes and objects. These features help in building modular, reusable, and
maintainable code.
• Key Concepts in OOP with PHP
• class – Defines a blueprint for an object.
• new – Creates a new instance (object) of a class.
• public, private, protected – Access modifiers that control visibility.
• static – Declares properties and methods that belong to the class rather than an instance.
• extends – Enables inheritance, allowing one class to inherit properties/methods from
another.
• implements – Implements an interface, ensuring a class follows a specific structure.
class Animal {
public $name; // Public property
• PHP provides structured error handling through “try”, “catch”, “throw” and
“finally”,gracefully handle exceptions.
• Error Handling Keywords
• try – The block of code where an exception may occur.
• catch – Captures the thrown exception and executes error-handling code.
• throw – Manually triggers an exception
• finally – A block that executes regardless of whether an exception occurs.
• Example
• function divide($a, $b) {
• if ($b == 0) {
• throw new Exception("Division by zero is not allowed.");
• }
• return $a / $b;
• }
• try {
• echo divide(10, 0);
• } catch (Exception $e) {
• echo "Error: " . $e->getMessage();
• } finally {
• echo " - Execution complete.";
•
OUTPUT IN PHP
PHP PROVIDES ECHO AND PRINT FOR DISPLAYING OUTPUT.
• PHP allows including external files using include and require These help in modular development.
Behavior if file is missing Shows a warning and Shows a fatal error and
continues execution stops execution
CLASS MODIFIERS IN PHP