Unit-4 Basic Php
Unit-4 Basic Php
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”.
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.
FEATURES OF PHP
• Open Source – PHP is free to use and has a large developer community.
• Cross-Platform – Runs on Windows, Linux, macOS, and various web servers.
• Easy to Learn – Simple syntax and easy integration with HTML.
• Server-Side Scripting – PHP code executes on the server before sending output to
the browser.
• Supports Databases – Works with MySQL, PostgreSQL, SQLite, MongoDB, and
more.
• Embedded in HTML – Can be written inside HTML files for dynamic web pages.
• Object-Oriented Programming (OOP) – Supports OOP features like classes,
inheritance, and polymorphism.
• Secure – Provides built-in features to prevent SQL injection and attacks.
• Huge Library Support – Comes with many built-in functions and extensions for
various tasks.
• Session & Cookie Management – Easily handles user sessions and cookies.
• Error Handling – Provides error reporting and exception handling mechanisms.
• Supports File Handling – Can create, read, write, and delete files on the server.
• Flexible Integration – Works with JavaScript, XML, JSON, and RESTful APIs.
WORKING OF PHP
1. Client Requests a PHP Page
• The user enters a URL in the browser (e.g., www.example.com/index.php).
2. Request Sent to the Web Server
• The request reaches the web server (Apache, Nginx, IIS) where PHP is installed.
3. PHP Interpreter Processes the Script
• The PHP engine reads and executes the PHP code on the server.
• If there is database interaction, PHP queries the database (e.g., MySQL).
4. Generates HTML Output
• After execution, PHP generates HTML content based on the script’s logic.
5. Server Sends Response to Browser
• The web server sends the generated HTML page to the client’s browser.
6. Browser Displays the Page
• The browser renders the received HTML, and the user sees the final webpage.
Applications of PHP
PHP is widely used for various web applications due to its flexibility and efficiency. Some
common applications include:
1. Dynamic Websites & Web Applications – Used for interactive websites like blogs,
forums, and portals (e.g., WordPress, Joomla).
2. E-Commerce Platforms – Powers online stores such as WooCommerce, Magento, and
OpenCart.
3. Content Management Systems (CMS) – Popular CMS like WordPress, Drupal, and
Joomla are built with PHP.
4. Social Networking Sites – Facebook was originally developed in PHP (later
optimized with other technologies).
5. Online Booking Systems – PHP is used for hotel, airline, and event ticket booking
systems.
6. Database-Driven Applications – Used to create applications that store and retrieve
data from databases (MySQL, PostgreSQL).
WHY IS PHP CALLED SERVER SIDE SCRIPTING LANGUAGE?
PHP is called a server-side scripting language because its code is executed on the web
server, not on the client’s browser. The server processes the PHP script and sends the
output (usually HTML) to the client.Following are the key reasons:
Limitations of PHP
1. Slower Execution Compared to Compiled Languages – PHP is an interpreted
language, making it slower than compiled languages like C, C++, and Java.
2. Security Vulnerabilities – PHP is prone to SQL injection, XSS, and CSRF attacks if
not properly coded with security measures.
3. Not Ideal for Large-Scale Applications – PHP struggles with high-performance,
enterprise-level applications due to scalability and concurrency issues.
4. Weak Typing System – PHP automatically converts variable types, which can cause
unexpected behavior and bugs.
5. Difficulty in Debugging – PHP has fewer built-in debugging tools compared to
languages like Java or Python, making troubleshooting complex.
PHP SYNTAX
<?php
// PHP code goes here
?>
PHP COMMENTS
Comments in PHP are an essential aspect of programming that allows developers to add
explanatory or descriptive text within their code. Comments are not executed by the PHP
interpreter and are meant solely for human readers. PHP supports two types of comments:
single-line comments and multi-line comments. Single-line comments begin
with "//" or "#" and are used to comment out a single line of code. Multi-line comments
are enclosed between "/" and "/" and can span across multiple lines, allowing developers
to comment out larger blocks of code.
Hello World Program in PHP
A Hello World program is the simplest way to start with any programming language. In
PHP, it looks like this:
<?php
echo "Hello, World!";
?>
Explanation:
1. <?php – This is the PHP opening tag, which tells the server that PHP code starts here.
2. echo "Hello, World!"; –
o echo is a built-in PHP statement used to output text to the web page.
o "Hello, World!" is a string that will be displayed.
o The semicolon (;) is required to terminate the statement.
3. ?> (Optional Closing Tag) –
o If the PHP file only contains PHP code, the closing ?> tag is optional.
o If mixing PHP with HTML, you must close the tag.
▪ Variables:
• Variable in any programming language is a name given to a memory location
that holds a value.
• You can say that variables are containers for any type of values.
• There are some rules to write variable names in PHP.
Rules for variable names:
• Variable names in PHP start with a dollar ($) sign followed by the variable
name.
• Variable name can contain alphanumeric characters and underscore (_).
• Variable names must start with a letter or an underscore (_). (For eg: $abc,
$x1, $_g, $abc_1 etc.)
• Variable names cannot start with a number.
• Variable names are case-sensitive. (for eg: $x and $X are treated as two
different variables.)
• In PHP we don’t use any command to declare variables.
• A variable is created as soon as you assign a value to it.
• A variable takes a datatype according to the value assigned to it.
▪ Since we don’t have to specify datatypes for PHP variables, PHP is called as loosely
typed language.
▪ Case Sensitivity: PHP variable names are case-sensitive, meaning $name and $Name
are different variables.
▪ Avoid Reserved Words: Do not use PHP reserved words or keywords as variable
names (e.g., function, class, echo).
Example
<?php
$firstName = "Alice"; // Valid
$_age = 25; // Valid
<?php
$x=10;
echo $x;
?>
Scope of variables:
▪ Variables can be declared anywhere in the program.
▪ Scope of a variable is a part of the program where the variable is accessible.
▪ PHP has three different variable scopes:
▪ Local
▪ Global
▪ static
1. Local scope:
• A variable declared within a function has a local scope and can be accessed within a
function only.
• A function is a small program performing a particular task which is called when
required.
2. Global scope:
• A variable declared outside a function has a global scope and can be accessed outside
the function only.
• Actually global variables can be accessed anywhere using the global keyword.
3. Static scope:
• A variable declared with static keyword is said to have static scope within the
function.
• Normally when variables are executed, they lose their values or memory.
• But when a variable is declared as static, it doesn’t lose its value. It remains static
within multiple function calls.
function testScope() {
// Local variable (only accessible inside this function)
$localVar = 20;
echo "Local Variable inside function: $localVar<br>";
testScope();
testScope();
testScope();
Constants
In PHP, constants are identifiers for values that cannot be altered during script execution,
unlike variables. Defined using the define() function or the const keyword, they are
immutable and remain constant throughout the program. Typically uppercase, constants'
names start with a letter or underscore, followed by any combination of letters, numbers,
or underscores without special characters.
PHP DATATYPES
A data type describes a set of values and the operations possible on those values.
1. Scalar — These are the simplest data types, not made up of any other data type.
2. Compound — These are made up of scalar and possibly other compound data types.
3. Special — These are special types that aren't scalar, nor compound.
4. The four scalar data types are: integers, floats, strings, Booleans.
5. The compound types are arrays, objects, callables, iterables.
6. Finally, the two special types are: resources, and NULL.
Integers
Integers are simply whole numbers without a fractional part. Examples are -100, -
1, 0, 1, 100 and so on. An integer in PHP is signed and is 8 bytes large on a 64-bit machine,
and 4 bytes large on a 32-bit machine.
<?php
$x = 10;
$y = -1000;
TYPECASTING
A typecast tries to cast (convert) a given value to another one.A typecast is denoted by writing
the name of the type enclosed in parentheses (such as (int), where int is the name of the integer
data type), followed by the value to cast.
EXAMPLE
<?php
$x = '10';
The goal is to convert this string into a number so that we can reliably use it in arithmetic
expressions.The way we do so is by using an integer typecast on $x, as shown below:
<?php
$x = '10';
var_dump($x);
$x = (int) $x;
var_dump($x);
<?php
var_dump(is_int(10)); // true
var_dump(is_int(10.0)); // false
var_dump(is_int('10')); // false
?>
Floats
Examples of floats include -3.578, -2.1333333, 0.0, 10.5, 154848.00000004 and so on.
<?php
$f1 = 3.55;
$f2 = -0.62;
Strings
A string is a sequence of characters in PHP.A string in PHP can be denoted in two ways i.e. by
using a pair of single quotes ('') or a pair of double quotes ("").A pair of single quotes ('') creates
a string exactly as it is written — no processing involved within the content of the string. In
contrary to this, a pair of double quotes ("") creates a string that is processed for escape
sequences and interpolation.
EXAMPLE
<?php
// Single-quoted string isn't processed.
echo 'Hello\nWorld!';
// Double-quoted string is processed.
echo "Hello\nWorld!";
?>
OUTPUT
Hello\nWorld
Hello World!
ARRAY
An array is an ordered sequence of elements stored as a single entity in memory.
<?php
$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];
OUTPUT
Callables
Callables are simply values that can be called.
The most common kind of callables used in PHP is that of functions.
Iterables
Iterables allow us to abstractly create sequences by defining the code to generate the next item
in them.
Special types
The two special data types provided by PHP are NULL and the resource type.
NULL
The NULL type has only one possible value and that is, trivially, NULL.NULL is used to
represent the absence of a value.
RESOURCES
Resources in PHP are values literally representing given resources, such as files, streams,
database connections, and so on.
Control structures in PHP manage the flow of execution in a program. They are categorized
into:
In PHP, conditional statements are used to execute different blocks of code based on
conditions. The main types of conditional statements in PHP are:
1. if Statement
Syntax:
if (condition) {
// Code to execute if condition is true
}
2. if-else Statement
Executes one block if the condition is true, otherwise executes another block.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
<?php
$marks = 40;
if ($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
?>
Output:
Fail
3. if-elseif-else Statement
Syntax:
if (condition1) {
// Code if condition1 is true
} elseif (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example:
<?php
$grade = 85;
if ($grade >= 90) {
echo "A Grade";
} elseif ($grade >= 75) {
echo "B Grade";
} else {
echo "C Grade";
}
?>
Output:
B Grade
4. switch Statement
Used when you have multiple possible values for a single variable.
Syntax:
switch (variable) {
case value1:
// Code to execute if variable == value1
break;
case value2:
// Code to execute if variable == value2
break;
default:
// Code if no case matches
}
Example:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is near!";
break;
default:
echo "It's a regular day.";
}
?>
Output:
Start of the week!
Loops in PHP
Loops in PHP are used to execute a block of code repeatedly based on a condition. PHP
supports four main types of loops:
while Loop
Syntax:
while(condition) {
// Code to execute
do...while Loop
This loop executes the code at least once, then checks the condition.
Syntax:
do {
// Code to execute
} while (condition);
for Loop
Syntax:
// Code to execute
Loop termination in PHP means stopping the execution of a loop before it naturally completes.
This is done using loop control statements like break and continue.
Output:
12
Example of continue (Skips the current iteration and continues the loop)
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skips when i == 3
}
echo "$i ";
}
?>
Output:
1245
FUNCTIONS IN PHP
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.
We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.
Syntax
function functionname(){
//code to be executed
}
EXAMPLE 1
<?php
function hi()
{
echo "Bye";
Echo "<br>";
}
hi();
?>
<?php
function hi3($name,$age)
{
echo "Hi $name<br>";
echo "Your age is $age<br>";
}
hi3("Rimsy",32);
?>
PHP functions with default parameters allow you to define a default value for function
arguments.
<?php
function hi4($name="manisha")
{
echo "Hi $name<br>";
}
hi4("Rimi");
hi4();
?>
OUTPUT
We can create and use forms in PHP. To get form data, we need to use PHP superglobals
$_GET and $_POST.The form request may be get or post. To retrieve data from get request,
we need to use $_GET, for post request $_POST.
Get request is the default form request. The data passed through get request is visible on the
URL browser so it is not secured. You can send limited amount of data through get request.Let's
see a simple example to receive data from get request in PHP.
File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
FORM HANDLING USING POST METHOD
File: form1.html
<form action="welcome.php" method="post">
Name: <input type="text" name="name"/>
<input type="submit" value="Visit"/>
</form>
Form validation is a crucial step that needs to be completed before submitting data to the
database. This process is performed to prevent any errors or faulty data from being inserted
into the database. The HTML form includes various input fields such as email, text, checkbox,
radio button, etc. These input fields must be validated to ensure that the user enters only the
intended values and not incorrect ones.
<!DOCTYPE html>
<html>
<head>
<title>Simple PHP Form Validation</title>
</head>
<body>
<?php
// Step 1: Initialize variables
$name = $email = "";
$nameErr = $emailErr = "";
// Step 2: Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Step 3: Validate Name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = cleanInput($_POST["name"]);
}
PHP SUPERGLOBALS
Superglobals are built-in global arrays in PHP that provide easy access to request, session, and
environment data. These variables are accessible from anywhere in a script (functions, classes,
files) without needing to use global.
Example:
<?php
echo "Hello, " . $_REQUEST["name"];
?>
Example:
<?php
echo $_SERVER["PHP_SELF"]; // Current script file
echo $_SERVER["SERVER_NAME"]; // Server name
echo $_SERVER["REQUEST_METHOD"]; // Request method (GET/POST)
?>
Example:
upload.html
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file: <input type="file" name="fileToUpload">
<input type="submit" value="Upload">
</form>
upload.php
<?php
echo "File Name: " . $_FILES["fileToUpload"]["name"];
?>
PHP ARRAYS
Arrays in PHP are a type of data structure that allows us to store multiple elements of similar
or different data types under a single variable thereby saving us the effort of creating a different
variable for every data.
Types of Array in PHP
• Indexed or Numeric Arrays: An array with a numeric index where values are stored
linearly.
• Associative Arrays: An array with a string index where instead of linear storage, each
value can be assigned a specific key.
• Multidimensional Arrays: An array that contains a single or multiple arrays within it
and can be accessed via multiple indices.
<?php
// Indexed Array
$countries = ["USA", "UK", "Canada"];
echo "<br>";
// Multidimensional Array
$students = [
["id" => 1, "name" => "John", "grade" => "A"],
["id" => 2, "name" => "Emma", "grade" => "B"],
["id" => 3, "name" => "Liam", "grade" => "A"]
];
Multidimensional Array:
ID: 1, Name: John, Grade: A
ID: 2, Name: Emma, Grade: B
ID: 3, Name: Liam, Grade: A
PHP STRINGS
A string in PHP is a sequence of characters used to store text. Strings are one of the most
commonly used data types in PHP.
1. Declaring Strings in PHP
You can create strings using:
• Single Quotes (')
• Double Quotes (")
2. String Concatenation
<?php
$firstName = "John";
$lastName = "Doe";
echo $fullName;
?>
3. String Length
<?php
?>
<?php
?>
Output: Word Count: 3
5. Reverse a String
<?php
$str = "Hello";
echo strrev($str);
?>
Output: olleH
<?php
echo $newStr;
?>
<?php
echo strtolower($str);
?>
OUTPUT
HELLO WORLD!
hello world!
9. Comparing Strings
Example:
<?php
$str1 = "Hello";
$str2 = "hello";
if (strcmp($str1, $str2) == 0) {
} else {
?>
PHP REGEX
Regular Expressions (Regex) in PHP help in pattern matching and text searching.
Common Regex Functions in PHP
1. preg_match() – Finds the first match in a string
<?php
$pattern = "/hello/i"; // 'i' makes it case-insensitive
$text = "Hello World!";
if (preg_match($pattern, $text)) {
echo "Match found!";
} else {
echo "No match found.";
}
?>
Output: Match found!
2. preg_match_all() – Finds all matches in a string
<?php
$pattern = "/cat/";
$text = "The cat sat on a cat.";
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>
Output:
Array ( [0] => Array ( [0] => cat [1] => cat ) )
3. preg_replace() – Replaces text using regex
<?php
$pattern = "/apple/";
$replacement = "orange";
$text = "I love apple pie.";
echo preg_replace($pattern, $replacement, $text);
?>
🔹 Output: I love orange pie.
PHP NUMBERS
PHP supports different types of numbers:
• Integers (whole numbers)
• Floats (decimal numbers)
• Scientific notation (exponential format)
<?php
?>
<?php
?>
3. ceil() – Rounds Up
<?php
?>
<?php
echo floor(3.9); // Output: 3
?>
PHP errors occur when something is wrong in the script. Here are the main types of PHP errors: