0% found this document useful (0 votes)
20 views

UNIT-1 PHP

PHP (Hypertext Preprocessor) is an open-source, server-side scripting language used for web development, allowing dynamic and interactive web pages. It features cross-platform compatibility, easy database integration, and a supportive community, making it accessible for beginners and powerful for experienced developers. PHP's evolution includes several versions that enhance performance and functionality, and it can be embedded within HTML to create dynamic content.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

UNIT-1 PHP

PHP (Hypertext Preprocessor) is an open-source, server-side scripting language used for web development, allowing dynamic and interactive web pages. It features cross-platform compatibility, easy database integration, and a supportive community, making it accessible for beginners and powerful for experienced developers. PHP's evolution includes several versions that enhance performance and functionality, and it can be embedded within HTML to create dynamic content.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

UNIT-1

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.

How PHP Works


1. Client Request: A user requests a PHP page by entering a URL in their web browser.
2. Server Processing: The web server (e.g., Apache, Nginx) processes the PHP script and executes the
server-side code.
• Database Interaction (Optional): If the script includes database queries, PHP retrieves data from the
database.
• HTML Output: The PHP interpreter converts the script into HTML and sends it to the client’s browser.
EXAMPLE
• <?php
• echo "Hello, World!";
• ?>
WHAT IS A PHP FILE?

• 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

•X – Cross-platform (works on Windows, macOS, Linux),A – Apache (web server),M – MySQL/MariaDB


(database) P – PHP (server-side scripting language) and P – Perl (optional scripting language)
•Features of XAMPP:
•Works on multiple operating systems (Windows, macOS, Linux)
Comes with phpMyAdmin for database management
Supports Perl (in addition to PHP)
Has an easy-to-use control panel
Provides built-in FTP and mail servers
Whereas WAMP stands for W – Windows (works only on Windows OS), A – Apache (web server), M – MySQL
(database), P – PHP (server-side scripting language)
• Features of WAMP:
• Windows-only compatibility (designed specifically for Windows)
Comes with phpMyAdmin for easy database management
Provides a graphical interface to manage Apache, MySQL, and PHP
Supports multiple PHP versions
• Steps to Install WAMP on Windows:
• Download WAMP Server
Go to the official WAMP website
Click on “DOWNLOADS” and choose the appropriate version
• Running the Installer.
Once the download is run the installer , follow the instructions carefully
• Launch WAMP Server:
After installation is complete , launch the WAMP server application and try to run application
• Test the installation
Test it is properly running also try to create a php file to ensure everything is running smootly
• Test PHP
• Create php file with .exe extension and try running it
SAMPLE PAGE IN PERSONAL HOME PAGE:
1. Create HTML page
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to Our Website</h1>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br><br>
<input type="submit">
</form>
</body>
</html>
• Create a PHP File
• Open a Text Editor like Notepad or Notepad++
• <!DOCTYPE html>
• <html>
• <body>
• <h1>Welcome <?php echo $_POST["name"]; ?>
• </h1>
• </body>
• </html>
• Start WAMP
• Access the form by opening browser and type http://localhost /myfirstPHP.html
• Enter the data and click submit
• Proccessing the POST request
• Display Result
WELCOME NAME THAT YOU SUBMITTED
EMBEDDING PHP CODE IN YOUR SCRIPT
• Php is a versatile scripting language commonly used for web development when php is
intergrated with web pages , it allow for creation of dynamic ,content and interaction with
database, form processing, and more , the server process the php code before sending the
result to html client side which will make the web application more interactive and dynamic
• These are some of various ways to integrate PHP with HTML
Inline PHP
What it is
Inline PHP means embedding PHP code directly inside an HTML file. This is done using PHP tags
<?php…..?> When the server processes the page, it executes the PHP code and outputs the
result as part of the HTML.
<html>
<body>
<h1>Welcome, <?php echo "User"; ?>!</h1>
</body> </html>
• PHP File Inclusion:
PHP file inclusion lets you split your code into multiple files. You can put
common parts (like headers, footers, or navigation menus) in separate files
and include them in your main file. This promotes code reusability and
modularity.
• <?php include 'header.php'; ?>
• <p>Main content of the page.</p>
• <?php include 'footer.php'; ?>
PHP within Script Tags
• Sometimes you need PHP to generate JavaScript code dynamically. By placing
PHP code inside <script> tags, you can generate client-side JavaScript that
includes dynamic server-side data.
• <script type="text/javascript">
• <?php
• echo "alert('Current server time is " . date("h:i:s A") . "');";
• ?> </script>
PHP in CSS
• What it is:
You can use PHP to generate CSS styles dynamically. This is useful if you want styles to change
based on server-side conditions or generate random styles.
• <style type="text/css“>
<?php
// Generate a random color for the background on each page load.
echo "body { background-color: #" . dechex(rand(0, 16777215)) . "; }";
?> </style>
PHP in HTML Attributes:
• What it is:
PHP can also be used inside HTML attribute values to generate dynamic URLs,
image sources, or other attribute values based on server-side data.
• <a href="profile.php?id=<?php echo $user_id; ?>">View Profile</a>
• Dynamic Content Generation:
PHP allows you to generate content on the fly based on user input, database queries, or
server-side logic. This means your website can display personalized or up-to-date information
automatically.
• Seamless Integration with HTML:
PHP code can be embedded directly within HTML. This makes it easy to mix static and
dynamic content, allowing for more flexible page designs.
• Customization and Personalization:
By embedding PHP in HTML attributes and CSS, you can customize the look and functionality
of your website based on dynamic data. This enables personalized user experiences, such as
changing themes or styles on the fly.
• Code Reusability and Modularity:
With PHP file inclusion (using include and require) you can separate common elements like
headers, footers, or navigation menus into separate files. This not only makes your code
easier to maintain but also promotes reusability across different pages.
• Enhanced Interactivity:
PHP can work alongside client-side scripts like JavaScript to create interactive elements. For
example, it can generate JavaScript dynamically to reflect server-side data, enhancing the
user experience.
• Simplified Server-Side Logic:
Embedding PHP code directly within your web pages allows for easier implementation of
server-side processes like form handling, user authentication, and database interactions.
WRITING COMMENTS IN 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!";

• // With proper whitespace - clearer:


• $a = 5;
• echo "Hello World!";
• // Variable assignments with different whitespace usage:
• $variable1=10; // No space around the assignment operator (less readable)
• $variable2 = 20; // Single space around the assignment operator (clear and preferred)
• $variable3 = 30; // Multiple spaces (readable, but consistency is key)
• $variable4
• = 40; // Line break and indentation; while valid, it should be used consistently
• ?>
• Assignment Operators:
Adding spaces around operators (like =) improves readability. The code functions the same $a=5; is
generally preferred over $a = 5; because it’s easier to read.
• Variable Declarations:
Consistent whitespace helps developers quickly understand what each line is doing. While you can add
multiple spaces, it's best to stick to one style to maintain consistency.
• Example 2: Using Whitespace in Function Definitions
• <?php
• // Define a function to calculate the sum of two numbers
• function calculateSum($num1, $num2) {
• // Calculate the sum
• $sum = $num1 + $num2;

• // Return the result
• return $sum;
• }
• // Call the function and store the result in a variable
• $result = calculateSum(5, 3);

• // Output the result


• echo "The sum of 5 and 3 is: " . $result;
• ?>
• Function Definition:
• The function calculatesum() is defined with proper indentation and spacing. Each logical
block (the function declaration, the code within the function, and the return statement) is
separated by line breaks and indented appropriately.
• Variable Assignment and Output:
Using spaces around the assignment operator and concatenation operator ( the . In the
echo statements) makes the code more legible. This consistent formatting helps both
current and future developers understand the flow of the program.
PHP BASIC SYNTAX - RULES AND
CONVENTIONS
Statements Terminated by Semicolons:
• Every individual PHP statement must end with a semicolon “;”
• The semicolon tells the PHP interpreter, "This is the end of this instruction." Without it, the interpreter
can’t tell where one statement ends and another begins, which will lead to syntax errors.
• <?php
• $name = "Snigdha";
• $age = 20;
• echo "My name is $name and I am $age years old.";
• ?>
The “$” Symbol for Variables
• What It Means:
• In PHP, every variable name starts with a dollar sign ($).
• This is a unique feature in PHP that immediately tells the interpreter that you’re dealing with
a variable.
• <?php
• // Declaring different types of variables:
• $number = 42; // An integer variable
• $greeting = "Hello"; // A string variable
• $colors = array("Red", "Green", "Blue"); // An array variable

• // Using the variables:


• echo $greeting . ", the number is " . $number;
• ?>
Whitespace and Indentation
• What It Means:
• Whitespace includes spaces, tabs, and newline characters.
PHP’s Flexibility: The PHP interpreter generally ignores extra whitespace. This
means
<?php //
All three lines below work the same way:
$a=5;
$a = 5;
$a = 5;
?>
.
• Case Insensitivity in Function Names:
• What It Means:
• In PHP, function names are not case sensitive. This applies to both built-in functions and user-defined
functions.
• You can call the same function using different cases, and PHP will treat them as the same function.
• <?php
• $string = "Hello World";

• // Both of these calls refer to the same built-in functions:


• echo StrToLower($string); // Outputs: hello world
• ECHO STRTOUPPER($string); // Outputs: HELLO WORLD
• ?>
Variable Names Are Case-Sensitive
What It Means:
• What It Means:
• Unlike function names, variable names in PHP are case sensitive.
• This means that $variable, $Variable, $VARIABLE all the three are treated in different ways
• <?php
• $name = "Srikanth";
• $Name = "Bhagya";

• echo $name; // Outputs: Srikanth


• echo $Name; // Outputs: Bhagya
• ?>
• Code Blocks Defined Using Curly Braces:
• What It Means:
• Code blocks in PHP are defined using curly braces({})
• They are used to group a set of statements together, such as within functions, loops, and
conditionals.
• <?php
• // Defining a function with a code block:
• function printNumbersFunction() {
• echo "The numbers are: ";

• // A code block within a for loop:
• for ($i = 1; $i <= 10; $i++) {
• echo $i . " ";
• }
• }

• // Calling the function to display the numbers:


• printNumbersFunction();
• ?>
DATA TYPES IN PHP

• 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

A function is a reusable block of code that performs a specific task.


• function – Declares a function.
• return – Sends a value back from a function.
function greet() {
echo "Hello, World!";
}

greet(); // Calling the function


function add($a, $b) {
return $a + $b;
}

echo add(5, 3); // Output: 8


CLASSES AND OBJECTS 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

public function __construct($name) {


$this->name = $name;
}

public function speak() {


return "This is an animal.";
}
}

$dog = new Animal("Dog");


echo $dog->speak(); // Output: This is an animal.
ERROR HANDLING IN PHP

• 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 provides echo and print for displaying output.

FEATURE ECHO PRINT


Can output multiple values YES (echo “hello”, “world” NO ( print “hello” “world”)
may show error
Return value No value Return 1
Speed Slightly fast Slightly slow
INCLUDE FILES IN PHP

• PHP allows including external files using include and require These help in modular development.

FEATURE INCLUDE REQUIRE

Behavior if file is missing Shows a warning and Shows a fatal error and
continues execution stops execution
CLASS MODIFIERS IN PHP

Class modifiers control how classes and methods behave.


• static – Methods and properties that belong to the class, not an instance.
• abstract – Defines an abstract class that must be extended but cannot be instantiated.
• final – Prevents class inheritance and method overriding.

Defining Constants in PHP


PHP provides define() and const to declare constants.
Feature Define() const
Syntax Define(‘name’,’value’)l; Const NAME = ‘Value’;
Scope global Class or global
Can be used in class no yse

You might also like