Module 5
Module 5
PHP, which stands for Hypertext Preprocessor, is a widely used server-side scripting
language designed for web development. It has a long history and has evolved
signi cantly since its inception. Here are the origins and uses of PHP:
Origins of PHP:
• Creation by Rasmus Lerdorf (1994): PHP was originally created by Danish-
Canadian programmer Rasmus Lerdorf in 1994. It began as a set of Common
Gateway Interface (CGI) binaries written in the C programming language to track
visits to his online resume.
• PHP/FI (1995): Rasmus released PHP/FI (Personal Home Page/Forms Interpreter)
in 1995, which included a wider range of functionality. It allowed the creation of
simple dynamic web pages and the ability to interact with databases.
• Introduction of PHP 3 (1998): The next major release was PHP 3, which
introduced a more robust language structure and support for interacting with
databases like MySQL.
• Zend Engine (1999): PHP 4 incorporated the Zend Engine, a scripting engine for
PHP written by Andi Gutmans and Zeev Suraski. This signi cantly improved the
performance and capabilities of PHP.
• PHP 5 and Object-Oriented Programming (2004): PHP 5 introduced extensive
support for object-oriented programming (OOP) and brought improvements in
performance, error handling, and support for XML.
• PHP 7 (2015): PHP 7 marked a signi cant leap in performance with the introduction
of the Zend Engine 3. It brought improvements in speed, memory usage, and
introduced features like scalar type declarations and the spaceship operator.
• PHP 8 (2020): PHP 8 continued the evolution of the language, introducing features
like the Just-In-Time (JIT) compiler, union types, named arguments, and more.
Uses of PHP:
• Web Development:
1. Server-Side Scripting: PHP is primarily used for server-side scripting to
generate dynamic web pages. It can be embedded directly into HTML code.
2. Web Applications: PHP is used to develop web applications, from simple
websites to complex content management systems (CMS) like WordPress,
Joomla, and Drupal.
• Database Interaction:
1. MySQL Integration: PHP has strong support for interacting with MySQL
databases. It is frequently used to perform database operations, such as inserting,
updating, and retrieving data.
• User Authentication and Authorization:
1. PHP is commonly used to implement user authentication systems, managing
user sessions, and controlling access to various parts of a website or web
application.
• Server-Side Utilities:
1. File Handling: PHP can be used for le handling and manipulation on the
server, allowing applications to read, write, and modify les.
• API Development:
fi
fi
fi
fi
fi
1. PHP can be used to develop server-side components of RESTful APIs,
allowing communication between different web services and applications.
• Command-Line Scripting:
1. PHP can be executed from the command line, making it suitable for creating
command-line scripts and automation tasks.
• Content Management Systems (CMS):
1. Many popular CMS platforms, such as WordPress, are built using PHP. It
allows developers to create customizable and dynamic websites without extensive
coding.
• E-commerce Applications:
1. PHP is widely used in the development of e-commerce applications, enabling
the creation of online stores, shopping carts, and payment processing systems.
Overview of PHP
PHP, which originally stood for "Personal Home Page," is a widely used server-side
scripting language designed for web development. Over the years, its meaning has
evolved to "Hypertext Preprocessor." Here's an overview of PHP:
Key Characteristics:
• Server-Side Scripting: PHP is a server-side scripting language, meaning it is
executed on the server before the result is sent to the client's web browser. It is
used to generate dynamic content, interact with databases, and perform various
server-side tasks.
• Open Source: PHP is an open-source language, and its source code is freely
available. This fosters collaboration and community-driven development, resulting in
continuous improvements and updates.
• Cross-Platform Compatibility: PHP is platform-independent and can run on
various operating systems, including Windows, macOS, Linux, and more. It is
compatible with different web servers, such as Apache, Nginx, and Microsoft IIS.
• Interoperability: PHP can easily integrate with various databases (MySQL,
PostgreSQL, SQLite), web servers, and other technologies. It supports numerous
protocols, making it versatile for web development.
• Ease of Learning: PHP has a syntax that is relatively easy to learn, especially for
those with a background in C-style languages. Its simplicity makes it accessible for
beginners while providing powerful features for advanced users.
• HTML Embedded: PHP code is embedded directly within HTML, allowing
developers to mix dynamic server-side logic with static HTML content. This makes it
convenient for creating dynamic web pages.
• Extensibility: PHP supports extensions and modules that enhance its functionality.
These extensions cover a wide range of tasks, from image processing to encryption
and beyond.
• Large Community: PHP has a vast and active community of developers, which
contributes to extensive documentation, libraries, frameworks, and support forums.
The community-driven nature ensures ongoing support and improvement.
Evolution:
• PHP 3 (1998): Initial version with increased functionality beyond its original purpose
of tracking online resume views.
• PHP 4 (2000): Introduction of the Zend Engine, providing better performance and
additional features.
• PHP 5 (2004): Signi cant improvements, including support for object-oriented
programming (OOP), better error handling, and enhanced XML support.
• PHP 7 (2015): Major performance improvements, reduced memory usage, and the
introduction of features like scalar type declarations, return type declarations, and
the spaceship operator.
• PHP 8 (2020): Continued improvements with the introduction of the Just-In-Time
(JIT) compiler, union types, named arguments, and other enhancements.
Use Cases:
• Web Development: PHP is a cornerstone of web development, commonly used for
building websites, web applications, and dynamic content.
• Content Management Systems (CMS): Many popular CMS platforms, including
WordPress, Joomla, and Drupal, are built with PHP.
• E-commerce: PHP is widely used in developing e-commerce solutions, facilitating
the creation of online stores, shopping carts, and payment processing systems.
• Server-Side Scripting: PHP is employed for various server-side scripting tasks,
such as form processing, user authentication, and data manipulation.
• API Development: PHP can be used to develop the server-side components of
RESTful APIs, enabling communication between different services and applications.
• Command-Line Scripting: PHP scripts can be executed from the command line,
making it suitable for automation and scripting tasks.
PHP has a syntax that is easy to learn, especially for those with a background in C-style
languages. Here are some general syntactic characteristics of PHP:
1. Script Tags:
<?php
// PHP code here
?>
Comments:
• PHP supports both single-line (//) and multi-line (/* */) comments.
<?php
// This is a single-line comment
/*
This is a multi-line comment
fi
spanning multiple lines
*/
?>
Variables:
<?php
$name = "John";
$age = 25;
?>
Data Types:
• PHP has dynamic typing, meaning you do not need to declare the data type
of a variable.
• Common data types include strings, integers, oats, booleans, arrays, and
objects.
<?php
$name = "John"; // String
$age = 25; // Integer
$height = 5.9; // Float
$isStudent = true; // Boolean
$colors = array("Red", "Green", "Blue"); // Array
?>
Strings:
<?php
$name = "John";
echo 'Hello, ' . $name . '!'; // Single-quoted
echo "Hello, $name!"; // Double-quoted with variable interpolation
?>
Operators:
Control Structures:
• PHP supports common control structures like if statements, loops (for, while,
do-while), and switch statements.
<?php
$x = 10;
if ($x > 0) {
echo "Positive";
} else {
echo "Non-positive";
}
// Loop
for ($i = 0; $i < 5; $i++) {
echo $i;
}
?>
Functions:
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("John");
?>
Arrays:
<?php
include "header.php";
require "functions.php";
?>
Output in php
if Statement:
if ($x > 5) {
echo "x is greater than 5";
}
?>
if-else Statement:
The if-else statement allows you to execute one block of code if the
condition is true and another block if the condition is false.
<?php
$x = 10;
if ($x > 5) {
echo "x is greater than 5";
} else {
echo "x is not greater than 5";
}
?>
if-elseif-else Statement:
This statement allows you to test multiple conditions and execute
different blocks of code based on the rst condition that is true.
<?php
$x = 10;
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "It's the start of the week";
break;
case "Friday":
echo "It's almost the weekend";
break;
default:
echo "It's just another day";
}
?>
while Loop:
The while loop executes a block of code as long as the speci ed
condition is true.
<?php
$i = 1;
for Loop:
The for loop is used to iterate a block of code a speci ed number of
times.
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
fi
fi
}
?>
foreach Loop:
The foreach loop is used to iterate over elements in an array.
<?php
$colors = array("red", "green", "blue");
Arrays in php
1. Numeric Arrays:
Numeric arrays use sequential numbers as keys.
<?php
// Accessing elements
Associative Arrays:
Associative arrays use named keys.
<?php
$assocArray = array(
);
$assocArray = [
];
// Accessing elements
Multidimensional Arrays:
Arrays can contain other arrays, creating multidimensional arrays.
<?php
$multiArray = array(
array(1, 2, 3),
);
// Accessing elements
Array Functions:
PHP provides a variety of built-in functions to manipulate arrays.
<?php
$numbers = [1, 2, 3];
// Adding an element
array_push($numbers, 4);
// Merging arrays
$newArray = array_merge($numericArray, $assocArray);
?>
Functions in PHP
De ning a Function:
You can de ne a function using the function keyword. The basic
syntax is as follows:
<?php
function greet($name) {
echo "Hello, $name!";
}
Function Parameters:
Functions can accept parameters (input values). These parameters
are listed within the parentheses after the function name
<?php
$sum = $a + $b;
return $sum;
?>
fi
fi
fi
Variable Scope:
Variables de ned inside a function have local scope, meaning they
are only accessible within that function. You can use the global
keyword to access global variables.
<?php
function example() {
global $globalVar;
echo $globalVar;
In PHP, you can use various functions and techniques for pattern matching. Here are
some commonly used methods:
1. Regular Expressions:
PHP supports regular expressions through the preg_match() function. Regular
expressions allow you to de ne complex search patterns. Here's a simple example:
if (preg_match("/Hello/", $text)) {
}
fi
fi
Regular Expressions in PHP:
Regular expressions, often abbreviated as regex or regexp, are sequences of characters
that de ne a search pattern. They are particularly useful for complex pattern matching and
manipulation of strings. PHP supports regular expressions through the preg_* functions.
preg_match() Function:
The preg_match() function is used to perform a pattern match on a string using a
regular expression. It returns true if the pattern is found in the string, and false otherwise.
if (preg_match("/hello/i", $text)) {
} else {
Capturing Groups:
Regular expressions can include capturing groups to extract speci c parts of a matched
string. For example:
} else {
fi
fi
fi
fi
fi
echo "Phone number not found!";
<?php
$input = "[email protected]";
if (fnmatch("abc*", $input)) {
echo "Matched user email prefix!";
} else {
echo "No match found.";
}
?>
3. String Functions:
PHP provides various string functions that can be used for basic pattern matching. For
instance, you can use strpos() to check if a substring is present in another string:
$needle = "World";
} else {
}
4. Pattern Matching with strstr() and stristr():
The strstr() function is used to nd the rst occurrence of a substring, and stristr()
is case-insensitive. Both can be used for simple pattern matching:
$var1= "Hello, World!";
$var2= "World";
} else {
HTML Forms:
HTML forms are used to collect and submit user input on web pages. They are created
using the <form> element and can contain various types of input elements such as text
elds, radio buttons, checkboxes, and buttons. The action attribute in the form speci es
the URL to which the form data will be sent, and the method attribute determines how the
data will be submitted (GET or POST).
HTTP Methods:
• GET Method:
• Submits form data as part of the URL.
• Limited data capacity (URL length restrictions).
• Data is visible in the URL.
• Suitable for non-sensitive data retrieval.
• POST Method:
• Submits form data in the request body.
• No URL length limitations.
• Data is not visible in the URL.
• Suitable for sensitive data and larger amounts of data.
fi
fi
fi
fi
3. PHP Form Handling:
Superglobals:
• $_GET: Retrieves form data submitted with the GET method.
• $_POST: Retrieves form data submitted with the POST method.
• $_REQUEST: Retrieves data from both GET and POST methods.
$name = $_POST[“name"];
$email = $_POST[“email"];
if ($_SERVER["REQUEST_METHOD"] == "POST")
Files in PHP
PHP provides various functions to handle les. Some common le-related operations
include reading from and writing to les, checking le existence, deleting les, etc. Here
are some examples:
• Reading from a le:
$ leContent = le_get_contents(‘example.txt');
Writing to a le:
Checking le existence:
if ( le_exists('example.txt')) {
echo 'File exists!';
} else {
echo 'File does not exist.';
}
Deleting a le:
unlink(‘example.txt');
Appending to a le:
Cookies in PHP
Cookies are small pieces of data that can be stored on the user's computer. They are
commonly used to store user preferences, session information, and other data.
Setting a cookie:
In this example, a cookie named 'user' is set with the value 'John Doe', and it will expire in
one hour (time() + 3600). The last parameter '/' indicates that the cookie is available
across the entire domain.
Accessing a cookie:
$username = $_COOKIE[‘user'];
This retrieves the value of the 'user' cookie and assigns it to the $username variable.
Deleting a cookie:
if (isset($_COOKIE['user'])) {
echo 'Cookie exists!';
} else {
echo 'Cookie does not exist.';
}
fi
fi
fi
fi
fi
fi
Difference between JavaScript and PHP
PHP
JavaScript
Currently, it is a full-stack programming It is a server-side
language. It means it can serve both the scripting language. It
client as well as server sites. serves only the
backend of the
website.
It is supportable by every web browser, It is supportable on
such as Mozilla, Google Chrome, and Windows, Linux, Mac,
many more. etc. platforms.
Supported by IIS,
Apache, and Lighttpd
web servers.
It carries less securable code. PHP code is highly
securable.
It requires an environment for accessing It allows easy and
the database. direct access to the
database.
T h e c o d e i s w r i t t e n w i t h i n The code is written
<script>...<script> tags. within <?php....?> tag.
Earlier, javascript was able to create A PHP program is able to
interactive pages for the clients. But, at generate dynamic pages,
send cookies, receive
present, it is able to build real-time games
cookies, collect form
and applications, mobile applications, too.
data, etc.
The extension used to save an external Files are saved using
javascript le is '.js'. '.php' extension.
We can embed the js code in HTML, XML, We can embed the
and AJAX. PHP code only with
HTML.
It supports fewer features. It supports more
advanced features as
compared to
JavaScript.
fi
Popular frameworks of JavaScript are Popular frameworks of
Angular, React, Vue.js, Meteor, etc. PHP are Laravel,
Symfony, FuelPHP,
CakePHP, and many
more.
Websites built in JavaScript are Twitter, Websites built in PHP
LinkedIn, Amazon, etc. are Wordpress,
Tumblr, MailChimp,
iStockPhoto, etc.