PHP
Unit – 1
Introduction to PHP
PHP (Hypertext Preprocessor) is an open-source, server-side scripting language widely
used for developing dynamic and interactive web pages. It is embedded within HTML and
executed on the server, which generates HTML that is then sent to the client’s browser. PHP
is known for its simplicity, flexibility, and efficiency in web development.
Evolution of PHP
1. 1994 – Creation:
PHP was created by Rasmus Lerdorf in 1994 to track visits to his online resume.
Initially, it was called Personal Home Page Tools (PHP Tools).
2. 1995 – PHP/FI (Forms Interpreter):
Rasmus released the source code to allow others to use and improve it. This version
supported simple form handling and database interaction.
3. 1997 – PHP 2.0:
A rewrite of the parser by Andi Gutmans and Zeev Suraski made PHP a more robust
scripting language. It became known as PHP/FI 2.0.
4. 1998 – PHP 3.0:
The official release of PHP 3.0 marked a major improvement with support for
multiple databases, protocols, and object-oriented programming concepts. The name
was changed to PHP: Hypertext Preprocessor (a recursive acronym).
5. 2000 – PHP 4.0:
Introduced the Zend Engine, which improved performance and modularity. It also
added better session handling and output buffering.
6. 2004 – PHP 5.0:
Added advanced object-oriented programming (OOP) features, exception handling,
and MySQLi extension.
7. 2015 – PHP 7.0:
Offered major performance improvements, reduced memory usage, and introduced
scalar type declarations.
8. 2020 onwards – PHP 8.0 and above:
Introduced features like Just-In-Time (JIT) compilation, union types, and attributes,
making PHP faster and more powerful for enterprise applications.
Comparison of PHP with Other Languages
JSP (Java Python
Feature PHP [Link]
Server Pages) (Django/Flask)
Windows
Platform Cross-platform Cross-platform Cross-platform
(mainly)
Licensed
Cost Free & Open Source Free Free
(Microsoft)
Database Multiple (MySQL,
Limited Multiple Multiple
Support PostgreSQL, etc.)
Ease of
Easy Moderate Moderate Easy
Learning
Performance High (PHP 7+) High Moderate High
Community
Very large Medium Medium Large
Support
Interfaces to External Systems
PHP can interface (connect and communicate) with a variety of external systems:
1. Databases:
MySQL, PostgreSQL, Oracle, SQLite, MongoDB, etc.
2. Web Services / APIs:
PHP supports REST and SOAP APIs for data exchange between web applications.
3. File Systems:
PHP can read, write, upload, and manipulate files on the server.
4. Email Systems:
PHP’s mail() function and libraries like PHPMailer can send automated emails.
5. External Libraries / Tools:
PHP can integrate with C/C++ extensions, Java, .NET, and Python via APIs or
bridging tools.
Hardware and Software Requirements
Hardware Requirements
• Processor: Minimum Pentium IV or higher
• RAM: Minimum 512 MB (1 GB or more recommended)
• Hard Disk: At least 200 MB free space for PHP and web server
• Internet Connection: Required for testing and online projects
Software Requirements
• Operating System: Windows / Linux / macOS
• Web Server: Apache / Nginx / IIS
• Database: MySQL or MariaDB
• PHP Interpreter: PHP 7.0 or higher
• Package Bundles: XAMPP, WAMP, or LAMP for easy setup
PHP Scripting
A PHP script is a file containing PHP code, usually saved with a .php extension.
It is executed on the server-side, and the result (mostly HTML) is sent to the user’s browser.
Example:
<?php
echo "Welcome to PHP Programming!";
?>
This code prints a message on the web page.
Basic PHP Development Process
1. Write PHP code in a text editor (e.g., VS Code, Sublime, Notepad++)
2. Save the file with a .php extension
3. Place it inside the htdocs folder (for XAMPP) or www (for WAMP)
4. Start Apache server
5. Run the file in a browser using:
6. [Link]
Working of PHP Scripts
1. The user requests a PHP page via browser.
2. The web server (Apache) sends the request to the PHP interpreter.
3. PHP executes the script on the server.
4. The output (HTML) is sent back to the browser.
Example flow:
Client → Request → Web Server → PHP Interpreter → Output → Client
Basic PHP Syntax
PHP code is written between <?php and ?> tags.
Example:
<?php
$greeting = "Hello, World!";
echo $greeting;
?>
• Comments:
• // Single-line comment
• /* Multi-line
• comment */
• Statements end with a semicolon ;
PHP Data Types
PHP is a loosely typed language, meaning you don’t need to declare data types explicitly.
Common data types include:
Type Description Example
String Sequence of characters "Hello"
Integer Whole numbers 42
Float/Double Decimal numbers 3.14
Boolean True or False true, false
Array Collection of values array(1,2,3)
Object Instance of a class new Car()
NULL Represents no value NULL
“Displaying Type Information: Testing for a Specific Data Type, Changing Type with
Set Type, Operators, Variable Manipulation, Dynamic Variables and Variable Scope.”
(Course Outcome: CO1 – Introduction to PHP)
Displaying Type Information
PHP allows developers to check and display the type of variables at runtime. This helps in
debugging and understanding how data is stored and interpreted by PHP.
Functions to Display Type Information
1. gettype() – Returns the data type of a variable.
2. $a = 10.5;
3. echo gettype($a); // Output: double
4. var_dump() – Displays both the type and value of a variable (useful for debugging).
5. $b = "Hello";
6. var_dump($b);
7. // Output: string(5) "Hello"
8. print_r() – Displays human-readable information about arrays and objects.
9. $arr = array(1, 2, 3);
10. print_r($arr);
11. // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )
Testing for a Specific Data Type
PHP provides a set of type-checking functions to verify the type of a variable.
Function Description Example
is_int() Checks if variable is an integer is_int(10) → true
is_float() Checks if variable is a float is_float(10.5) → true
is_string() Checks if variable is a string is_string("PHP") → true
is_bool() Checks if variable is boolean is_bool(true) → true
is_array() Checks if variable is an array is_array([1,2,3]) → true
is_object() Checks if variable is an object is_object($obj) → true
is_null() Checks if variable is NULL is_null($x) → true
Example:
$val = 100;
if (is_int($val)) {
echo "It is an integer.";
}
Changing Type with Set Type
PHP allows changing the data type of a variable dynamically using the settype() function.
Syntax:
settype(variable, type);
Example:
$x = "25"; // String
settype($x, "integer");
echo gettype($x); // Output: integer
Common Type Values Used:
• "integer"
• "double"
• "string"
• "boolean"
• "array"
• "object"
• "null"
Alternatively, type casting can also be used:
$y = "10.6";
$z = (int)$y; // Converts to integer
echo $z; // Output: 10
Operators in PHP
Operators are symbols used to perform operations on variables and values.
1. Arithmetic Operators
Used for mathematical operations.
Operator Description Example Result
+ Addition $a + $b Sum
- Subtraction $a - $b Difference
* Multiplication $a * $b Product
/ Division $a / $b Quotient
% Modulus $a % $b Remainder
** Exponentiation $a ** $b Power
2. Assignment Operators
Operator Description Example
= Assigns value $x = 10;
+= Add and assign $x += 5;
-= Subtract and assign $x -= 3;
*= Multiply and assign $x *= 2;
3. Comparison Operators
Operator Description Example Result
== Equal $a == $b True if equal
=== Identical (value + type) $a === $b True if both match
!= Not equal $a != $b True if not equal
> Greater than $a > $b True if greater
< Less than $a < $b True if smaller
4. Logical Operators
Operator Description Example
&& or and Logical AND $a && $b
` oror`
! Logical NOT !$a
5. String Operators
Operator Description Example Result
. Concatenation "Hello" . " World" "Hello World"
.= Append and assign $x .= "PHP"; Adds text to existing string
6. Increment / Decrement Operators
Operator Description Example
++$x Pre-increment Increments, then uses
$x++ Post-increment Uses, then increments
--$x Pre-decrement Decrements, then uses
Variable Manipulation
PHP allows several operations to manipulate variables:
1. isset($var) – Checks if a variable is defined and not NULL.
2. unset($var) – Deletes a variable.
3. empty($var) – Checks if a variable is empty (0, "", NULL, false).
4. gettype($var) / settype($var, type) – Get or change type.
5. var_dump($var) – Shows detailed information.
Example:
$a = 10;
if (isset($a)) echo "Variable exists.";
unset($a);
Dynamic Variables
A dynamic variable is a variable whose name is stored in another variable.
It is accessed using variable variables ($$).
Example:
$var = "name";
$$var = "Komal";
echo $name; // Output: Komal
Explanation:
Here $var contains the string "name".
$$var means $name.
Dynamic variables are useful when variable names need to be generated at runtime.
Variable Scope
The scope of a variable determines where it can be accessed in a program.
1. Local Scope
Variables declared inside a function are local to that function.
function test() {
$x = 10; // local
echo $x;
}
test();
2. Global Scope
Variables declared outside any function have global scope.
$x = 5;
function show() {
global $x;
echo $x;
}
show(); // Output: 5
3. Static Scope
Static variables retain their value between function calls.
function counter() {
static $count = 0;
$count++;
echo $count;
}
counter(); // 1
counter(); // 2
4. Superglobals
PHP has predefined global arrays that are accessible anywhere:
• $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, etc.
UNIT – II: PHP CONTROL STATEMENTS, FUNCTIONS, STRING
MANIPULATION, AND ARRAYS
CONTROL STATEMENTS [CO3]
Control statements in PHP determine the flow of program execution based on certain
conditions or loops.
1. if() and elseif() Conditional Statements
These statements execute code blocks based on conditions that evaluate to true or false.
Syntax:
if (condition) {
// Executes if condition is true
} elseif (another_condition) {
// Executes if this condition is true
} else {
// Executes if all conditions are false
}
Example:
$marks = 75;
if ($marks >= 90) {
echo "Grade A+";
} elseif ($marks >= 75) {
echo "Grade A";
} else {
echo "Grade B";
}
2. The switch Statement
Used to select one block of code among many based on the value of an expression.
Syntax:
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example:
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Friday":
echo "Weekend is near";
break;
default:
echo "Normal day";
}
3. The ? : (Ternary) Operator
A shorthand for simple if-else conditions.
Syntax:
(condition) ? value_if_true : value_if_false;
Example:
$age = 18;
$message = ($age >= 18) ? "Eligible to vote" : "Not eligible";
echo $message;
4. while() Loop
Executes a block of code while a condition remains true.
Syntax:
while (condition) {
// code
}
Example:
$i = 1;
while ($i <= 5) {
echo "Number: $i <br>";
$i++;
}
5. do...while Loop
Executes code at least once, then repeats while the condition is true.
Syntax:
do {
// code
} while (condition);
Example:
$i = 1;
do {
echo "Count: $i <br>";
$i++;
} while ($i <= 3);
6. for() Loop
Used when the number of iterations is known.
Syntax:
for (initialization; condition; increment) {
// code
}
Example:
for ($i = 1; $i <= 5; $i++) {
echo "Iteration $i <br>";
}
FUNCTIONS [CO3]
Functions are blocks of reusable code that perform specific tasks. They help reduce
repetition and improve program organization.
1. Function Definition
A function is defined using the function keyword.
Syntax:
function functionName() {
// code
}
Example:
function greet() {
echo "Welcome to PHP!";
}
greet(); // Function call
2. Returning Values from a Function
The return statement sends a value back to the caller.
Example:
function add($a, $b) {
return $a + $b;
}
echo add(5, 10); // Output: 15
3. Library (Built-in) Functions
PHP provides many predefined functions for string, math, and array operations.
Examples:
echo strlen("Hello"); // String length
echo sqrt(16); // Square root
echo date("Y-m-d"); // Current date
4. User-Defined Functions
Created by the programmer to perform custom tasks (like above add() or greet()).
5. Dynamic Function Calls
Function names can be stored in variables and called dynamically.
Example:
function hello() {
echo "Hello PHP!";
}
$func = "hello";
$func(); // Calls hello()
6. Default Arguments
Functions can have default parameter values if no value is passed.
Example:
function message($name = "Guest") {
echo "Hello, $name!";
}
message(); // Hello, Guest!
message("Komal"); // Hello, Komal!
7. Passing Arguments by Value
By default, PHP passes function arguments by value, meaning changes inside the function do
not affect the original variable.
Example:
function increment($num) {
$num++;
}
$x = 10;
increment($x);
echo $x; // Output: 10 (original unchanged)
STRING MANIPULATION [CO2]
Strings are sequences of characters. PHP offers powerful functions to format, modify,
compare, and split/join strings.
1. Formatting Strings for Presentation
Used for displaying data neatly.
Examples:
echo strtoupper("hello"); // HELLO
echo strtolower("HELLO"); // hello
echo ucfirst("php"); // Php
echo ucwords("php language"); // Php Language
2. Formatting Strings for Storage
Used to remove unwanted spaces or characters before storing data.
Examples:
$str = " PHP ";
echo trim($str); // Removes spaces from both ends
echo addslashes("It's me"); // Escapes special chars
3. Joining and Splitting Strings
• Joining (implode):
$arr = array("Apple", "Banana", "Mango");
echo implode(", ", $arr);
// Output: Apple, Banana, Mango
• Splitting (explode):
$str = "Red,Green,Blue";
print_r(explode(",", $str));
// Output: Array ( [0] => Red [1] => Green [2] => Blue )
4. Comparing Strings
Functions:
• strcmp(str1, str2) → Case-sensitive comparison
• strcasecmp(str1, str2) → Case-insensitive comparison
Example:
echo strcmp("Hello", "hello"); // Non-zero (different)
echo strcasecmp("Hello", "hello"); // 0 (same ignoring case)
ARRAYS [CO2]
An array is a collection of values stored under a single variable name.
1. Anatomy of an Array
Each element has a key (index) and a value:
$colors = array("Red", "Green", "Blue");
Here:
• Key: 0, 1, 2
• Values: "Red", "Green", "Blue"
2. Creating Arrays
(a) Indexed Array
Automatically indexed by numbers.
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[1]; // Output: Banana
(b) Associative Array
Uses named keys instead of numbers.
$marks = array("Komal" => 90, "Simran" => 85);
echo $marks["Komal"]; // Output: 90
3. Looping Through Arrays
(a) Using foreach Loop
$names = array("Aman", "Kiran", "Ravi");
foreach ($names as $n) {
echo $n . "<br>";
}
(b) Using each() with while()
(Older method – now rarely used but part of syllabus)
$fruits = array("Apple" => 100, "Banana" => 50);
while ($item = each($fruits)) {
echo $item['key'] . " costs " . $item['value'] . "<br>";
}
UNIT – III: Forms, File & Directory Handling, and Image
Generation in PHP
🧩 1. WORKING WITH FORMS
Forms are used to collect user input such as text, passwords, and selections from users on a
web page.
The data collected from an HTML form can be processed using PHP.
1.1 Creating and Working with Forms
A form in HTML is created using the <form> tag.
It can send data to a PHP script using GET or POST methods.
Example:
<form action="[Link]" method="post">
Name: <input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
Here, when the user submits the form, data is sent to [Link] for processing.
1.2 Super Global Variables
Superglobals are predefined PHP arrays that are always accessible, regardless of scope.
Variable Description
$_GET Collects data sent with the GET method (visible in URL).
$_POST Collects data sent with the POST method (hidden in URL).
$_REQUEST Collects data sent by both GET and POST.
$_SERVER Contains server and execution environment information.
$_FILES Handles file upload information.
$_SESSION Stores session variables.
$_COOKIE Stores cookie data.
$_ENV Environment variables.
1.3 Super Global Array Example
echo $_SERVER['PHP_SELF']; // Current script name
echo $_SERVER['SERVER_NAME']; // Server hostname
1.4 Importing User Input
When a form is submitted, PHP imports input data using $_GET or $_POST.
Example (POST Method):
$name = $_POST['username'];
echo "Welcome, $name!";
Example (GET Method):
$name = $_GET['username'];
echo "Hello, $name!";
1.5 Accessing User Input (Validation Example)
Always check if form data exists to prevent errors.
if (isset($_POST['username'])) {
$user = $_POST['username'];
echo "User: " . htmlspecialchars($user);
}
htmlspecialchars() prevents cross-site scripting (XSS) by converting HTML characters
to safe text.
1.6 Combining HTML and PHP Code
PHP can be embedded directly into HTML.
Example:
<form method="post">
Enter Name: <input type="text" name="name">
<input type="submit" value="Show">
</form>
<?php
if (isset($_POST['name'])) {
echo "Hello, " . $_POST['name'];
}
?>
1.7 Using Hidden Fields
Hidden fields are used to store additional data in a form without displaying it to the user.
Example:
<form method="post" action="[Link]">
<input type="hidden" name="userid" value="123">
<input type="submit" value="Continue">
</form>
1.8 Redirecting the User
Redirection sends the user to another page after an event (like login or form submission).
Example:
header("Location: [Link]");
exit();
Note: The header() function must be called before any HTML output.
📂 2. WORKING WITH FILES AND DIRECTORIES
File handling allows PHP scripts to create, read, write, and delete files stored on the server.
2.1 Understanding File & Directory
• File: A collection of data stored under a name (like [Link]).
• Directory (Folder): A container that holds files and subdirectories.
2.2 Opening and Closing a File
PHP provides the fopen() function to open files.
Syntax:
$handle = fopen("[Link]", "mode");
Common Modes:
Mode Description
r Read only
w Write only (erases existing content)
a Append (writes at the end)
r+ Read/Write
w+ Read/Write (erases existing content)
a+ Read/Write (appends content)
Example:
$file = fopen("[Link]", "w");
fwrite($file, "Hello PHP File Handling!");
fclose($file);
2.3 Copying, Renaming, and Deleting a File
Copy a File:
copy("[Link]", "[Link]");
Rename a File:
rename("[Link]", "[Link]");
Delete a File:
unlink("[Link]");
2.4 Working with Directories
Create a Directory:
mkdir("new_folder");
Remove a Directory:
rmdir("new_folder");
Read a Directory:
$dir = opendir(".");
while (($file = readdir($dir)) !== false) {
echo "File: $file <br>";
}
closedir($dir);
2.5 File Uploading
PHP supports file uploading via forms using the enctype="multipart/form-data"
attribute.
HTML Form:
<form action="[Link]" method="post" enctype="multipart/form-data">
Select file: <input type="file" name="myfile">
<input type="submit" value="Upload">
</form>
PHP Script ([Link]):
$target = "uploads/" . basename($_FILES["myfile"]["name"]);
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
2.6 File Downloading
To force the browser to download a file, use:
$file = "[Link]";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) .
'"');
readfile($file);
exit;
🖼️ 3. GENERATING IMAGES WITH PHP
PHP’s GD (Graphics Draw) library allows creation and manipulation of images
dynamically.
3.1 Basics of Computer Graphics
Computer graphics involve creating and manipulating visual content like lines, shapes, or
text.
PHP’s GD Library supports various image formats like JPEG, PNG, and GIF.
To use it, ensure GD extension is enabled in [Link].
3.2 Creating an Image
Example:
<?php
header("Content-type: image/png");
// Create a blank image
$image = imagecreate(300, 100);
// Allocate colors
$bg = imagecolorallocate($image, 0, 0, 255); // Blue background
$text = imagecolorallocate($image, 255, 255, 255); // White text
// Add text to image
imagestring($image, 5, 50, 40, "Hello PHP!", $text);
// Output image
imagepng($image);
imagedestroy($image);
?>
Explanation:
• imagecreate() → Creates a blank canvas.
• imagecolorallocate() → Defines colors using RGB values.
• imagestring() → Writes text onto image.
• imagepng() → Outputs the image in PNG format.
• imagedestroy() → Frees memory.
UNIT – IV: Database Connectivity with MySQL
1. Introduction to RDBMS
RDBMS (Relational Database Management System) is a software that stores data in the
form of tables (rows and columns) and allows relationships between those tables.
Key Concepts:
• Table: Collection of data organized in rows and columns.
• Row (Record/Tuple): A single entry in a table.
• Column (Field): A data attribute or property of a record.
• Primary Key: A unique identifier for each record in a table.
• Foreign Key: A field in one table that refers to the primary key in another table,
creating a relationship between tables.
• SQL (Structured Query Language): A language used to interact with databases (for
querying, updating, and managing data).
Advantages of RDBMS:
• Data consistency and integrity
• Reduced data redundancy
• Easy data access using SQL
• Multi-user access
• Data security and recovery
Popular RDBMS Software:
MySQL, Oracle, MS SQL Server, PostgreSQL, SQLite, etc.
2. Connecting PHP with MySQL Database
To work with databases in PHP, we use MySQLi (MySQL Improved) or PDO (PHP Data
Objects).
Step 1: Establish a Connection
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "student_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Explanation:
• mysqli_connect() — used to connect PHP with MySQL.
• Parameters:
o Server name – usually localhost
o Username – default root
o Password – blank for local server
o Database name – the database you want to connect to
• mysqli_connect_error() — returns the error message if connection fails.
3. Performing Basic Database Operations (DML)
DML = Data Manipulation Language, includes:
• INSERT
• DELETE
• UPDATE
• SELECT
(a) Inserting Data
<?php
$sql = "INSERT INTO students (name, age, course) VALUES ('Komal', 19,
'BCA')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
(b) Selecting Data
<?php
$sql = "SELECT id, name, course FROM students";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Course: "
. $row["course"]. "<br>";
}
} else {
echo "0 results";
}
?>
Explanation:
• mysqli_query() executes the SQL query.
• mysqli_num_rows() checks number of rows in result.
• mysqli_fetch_assoc() fetches data row by row in associative array format.
(c) Updating Data
<?php
$sql = "UPDATE students SET course='MCA' WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
?>
(d) Deleting Data
<?php
$sql = "DELETE FROM students WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
?>
4. Closing the Connection
<?php
mysqli_close($conn);
?>
This ensures that the database connection is properly terminated.
5. Example: Complete Program
<?php
$conn = mysqli_connect("localhost", "root", "", "college");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Insert data
$sql = "INSERT INTO student (name, age, marks) VALUES ('Riya', 20, 85)";
mysqli_query($conn, $sql);
// Retrieve data
$result = mysqli_query($conn, "SELECT * FROM student");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . " - " . $row['marks'] . "<br>";
}
mysqli_close($conn);
?>
6. PDO Method (Alternative Way)
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=college", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>