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

Unit-4 Basic Php

PHP, or Hypertext Preprocessor, is a server-side scripting language primarily used for web development and is open-source. It features cross-platform compatibility, easy integration with HTML, and supports various databases, making it suitable for dynamic websites and applications. PHP has evolved since its inception in 1995, with the latest stable version being 8.4.4 as of February 2025.

Uploaded by

roshan46g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit-4 Basic Php

PHP, or Hypertext Preprocessor, is a server-side scripting language primarily used for web development and is open-source. It features cross-platform compatibility, easy integration with HTML, and supports various databases, making it suitable for dynamic websites and applications. PHP has evolved since its inception in 1995, with the latest stable version being 8.4.4 as of February 2025.

Uploaded by

roshan46g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT-4

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.

How is PHP Platform Independent?


PHP is considered platform-independent because it can run on multiple operating systems
without modification. This is due to several key factors:
1. Interpreted Language – PHP code is not compiled into machine-specific binary files;
instead, it is interpreted by the PHP runtime engine, making it compatible across
different OS environments.
2. Cross-Platform Server Support – PHP works with various web servers like Apache,
Nginx, IIS, and LiteSpeed, which are available on Windows, Linux, macOS, and Unix.
3. Compatible with Multiple Databases – PHP supports MySQL, PostgreSQL, SQLite,
Oracle, and MongoDB, allowing flexibility in database management across different
platforms.
The official website of PHP is https://www.php.net.
History of PHP
PHP was introduced by Rasmus Lerdorf in 1995, the first version and participated in the later
versions. It is an interpreted language and it does not require a compiler. The language quickly
evolved and was given the name “PHP,” which initially named was “Personal Home Page.”
• PHP 1.0 (1995) – Personal Home Page Tools
• PHP 2.0 (1997) – PHP/FI (Forms Interpreter)
• Introduced a scripting language with basic functionality.
• PHP 3 (1998): The first version considered suitable for widespread use.
• PHP 4 (2000): Improved performance and the introduction of the Zend Engine.
• PHP 5 (2004): Added object-oriented programming features.
• PHP 6 was an experimental version of PHP that was never officially released as a stable
version.
• PHP 7 (2015): Significant performance improvements and reduced memory usage.
• PHP 8 (2020): Introduction of Just-In-Time (JIT) compilation, further enhancing
performance.
As of March 2025, the latest stable version of PHP is 8.4.4, released on February 13, 2025.

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:

• Executed on the Server:


• When a user requests a PHP page, the web server runs the PHP script and generates
an HTML response.
• Does Not Run in Browser:
• Unlike JavaScript, which executes in the client’s browser, PHP runs only on the
server.
• Dynamic Content Generation:
• PHP can fetch data from databases, process forms, manage sessions, and generate
dynamic content before sending it to the browser.
• Security:
• Since the PHP code is executed on the server, users cannot see the source code,
protecting sensitive logic and database queries.
• Database Interaction:
• PHP can connect to databases (e.g., MySQL, PostgreSQL) to fetch or store data
securely.

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 :The opening tag for php.


?>:The closing tag for php.

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.

PHP Embedded in HTML (Hello World Example)


You can integrate PHP into an HTML file like this:
<!DOCTYPE html>
<html>
<head>
<title>PHP Hello World</title>
</head>
<body>
<h1><?php echo "Hello, World!"; ?></h1>
</body>
</html>
Explanation:
1. The file starts with HTML structure (<!DOCTYPE html>, <html>, etc.).
2. Inside the <h1> tag, PHP code is embedded using <?php ... ?>.
3. echo "Hello, World!"; prints the text inside the <h1> tag.

SOFTWARE TOOLS REQUIRED TO RUN PHP


1. Web Servers (Required to Run PHP)
• Apache (Used in XAMPP, WAMP, LAMP) – Most popular web server for PHP.
• Nginx – High-performance alternative to Apache.
• LiteSpeed – Faster than Apache, often used for WordPress hosting.
• IIS (Internet Information Services) – Microsoft’s web server with PHP support.

2. Databases (For Storing Data)


• MySQL / MariaDB – Most commonly used with PHP.
• PostgreSQL – Advanced open-source alternative.
• SQLite – Lightweight database used for small applications.
• MongoDB – NoSQL database for scalable applications.

3. Code Editors & IDEs (For Writing PHP Code)


• VS Code – Lightweight with great PHP extensions.
• PHPStorm – Best professional IDE for PHP (paid).
• Sublime Text – Fast and customizable.
• Notepad++ – Simple and lightweight editor.

4. Version Control & Deployment


• Git & GitHub/GitLab/Bitbucket – For source code management.
• Docker – Containerization for PHP applications.

PHP VARIABLES AND CONSTANTS

▪ 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

$2ndPlace = "John"; // Invalid: Cannot start with a number


$class = "Phys"; // Valid, but avoid reserved words
?>
Variable declaration:
Variable is declared as follows:
$variable_name=value;
Example of variable declaration is given below:
$x=5;
$x is a variable and 5 is a value assigned to $x variable using assignment operator (=). The
assignment operator assigns the right hand side value to the left hand side variable in an
expression.
The variable name can be just alphabets or they can be some descriptive names
like $school_name, $names, $games etc.
In PHP we can print a value of variable using an echo statement as follows:

<?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.

Example(Local , Global and Static Scope)


<?php
// Global variable
$globalVar = 10;

function testScope() {
// Local variable (only accessible inside this function)
$localVar = 20;
echo "Local Variable inside function: $localVar<br>";

// Accessing global variable inside a function using 'global' keyword


global $globalVar;
echo "Global Variable inside function: $globalVar<br>";

// Static variable (retains its value across function calls)


static $staticVar = 0;
$staticVar++;
echo "Static Variable inside function: $staticVar<br>";
}

testScope();
testScope();
testScope();

echo "Global Variable outside function: $globalVar<br>";


?>
OUTPUT

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.

Create a PHP Constant


To create a constant in PHP, you can use either the define() function or the const
keyword. Here's an example of creating a constant using both methods:
Using define() function:
define('GREETING', 'Hello, World!');
echo GREETING;
Using const keyword:
const GREETING = 'Hello, World!';
echo GREETING; // Output: Hello, World!

Is PHP a Case-Sensitive Language?


PHP is partially case-sensitive, meaning some elements are case-sensitive while others are
not.
Case-Insensitive Elements in PHP:
1. Function Names – Built-in and user-defined function calls are case-insensitive.
2. Class Names (Before PHP 8.0) – Class names were case-insensitive before PHP 8.0,
but now they are case-sensitive.
3. Keywords (if, else, while, etc.) – PHP keywords and control structures are not case-
sensitive.

▪ Variables and Constants → Case-Sensitive


▪ Function Calls and Keywords → Case-Insensitive
▪ Class Names (PHP 8+) → Case-Sensitive

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;

echo '$x + $y: ', $x + $y, "\n";


echo '$x - $y: ', $x - $y, "\n";
echo '$x * $y: ', $x * $y, "\n";
echo '$x / $y: ', $x / $y, "\n";

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

Floats, or floating-point numbers, are numbers with a fractional part.

Examples of floats include -3.578, -2.1333333, 0.0, 10.5, 154848.00000004 and so on.
<?php

$f1 = 3.55;
$f2 = -0.62;

echo $f1 + $f2;


?>

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];

// Marks of third quiz.


echo $marks[2];
echo "<br>";

// Marks of sixth quiz.


echo $marks[5];
echo "<br>";
$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];
sort($marks);
print_r($marks);
?>

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

Control structures in PHP manage the flow of execution in a program. They are categorized
into:

1. Conditional Statements (Decision-Making)


2. Looping Statements (Repetitive Execution)

3. Jump Statements (Control Transfer)

PHP CONDITIONAL STATEMENTS

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

Executes code only if the condition is true.

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

Allows checking multiple conditions.

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:

1. while loop – Runs while a condition is true.

2. do...while loop – Runs at least once, then checks the condition.

3. for loop – Runs a fixed number of times.

4. foreach loop – Used specifically for arrays.

while Loop

Executes as long as the condition is true.

Syntax:

while(condition) {

// Code to execute

Example: Print numbers from 1 to 5


<?php
$num = 1;
while ($num <= 5) {
echo "Number: $num <br>";
$num++; // Increment the counter
}
?>

do...while Loop

This loop executes the code at least once, then checks the condition.

Syntax:

do {

// Code to execute

} while (condition);

Example: Print numbers from 1 to 5


<?php
$num = 1;
do {
echo "Number: $num <br>";
$num++;
} while ($num <= 5);
?>

for Loop

Runs a loop for a fixed number of times.

Syntax:

for(initialization; condition; increment/decrement) {

// Code to execute

Example: Print numbers from 1 to 5


<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>

foreach Loop (For Arrays)

Loops through each element of an array.


Syntax
foreach ($array as $value) {
// Code to execute for each element
}

Example: Print all car names in an array


<?php
$cars = ["Mercedes", "BMW", "Tesla"];
foreach ($cars as $car) {
echo "Car: $car <br>";
}
?>

LOOP TERMINATION IN PHP

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.

Example of break (Stops the loop when condition is met)


<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break; // Loop stops when i == 3
}
echo "$i ";
}
?>

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.

Advantage of PHP Functions

Code Reusability, Less code and easy to understand.

PHP User-defined Functions

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();
?>

EXAMPLE 2(WITH ONE PARAMETER)


<?php
function hi1($name)
{
echo "Hi $name<br>";
}
hi1("Rimsy");
?>

EXAMPLE 3(WITH TWO PARAMETERS)

<?php
function hi3($name,$age)
{
echo "Hi $name<br>";
echo "Your age is $age<br>";
}
hi3("Rimsy",32);
?>

EXAMPLE 4(FUNCTIONS WITH DEFAULT PARAMETER)

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

PHP FUNCTIONS RETURNING VALUE


<?php
function square($num)
{
return $num * $num;
}
echo "Square is ".square(8);
?>

PHP FORM HANDLING

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.

FORM HANDLING USING GET METHOD

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>

PHP FORM VALIDATION

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"]);
}

// Step 4: Validate Email


if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = cleanInput($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}

// Step 5: Function to clean user input


function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
?>
<!-- Step 6: Create a simple form -->
<h2>PHP Form Validation</h2>
<form method="post" action="">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span style="color:red;"><?php echo $nameErr; ?></span><br><br>
Email: <input type="text" name="email" value="<?php echo $email; ?>">
<span style="color:red;"><?php echo $emailErr; ?></span><br><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

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.

1. $_GET (Retrieves Data from URL Query Parameters)

• Used to collect data sent via GET method.

• Data is visible in the URL.

2. $_POST (Retrieves Data from HTTP POST)

• Used to collect data sent via POST method.


• Data is not visible in the URL, making it more secure.

3. $_REQUEST (Retrieves Data from Both GET & POST)

• Collects both GET and POST request data.

• Useful when the request method is unknown.

Example:
<?php
echo "Hello, " . $_REQUEST["name"];
?>

4. $_SERVER (Server & Execution Environment Information)

• Contains server and request details.

Example:
<?php
echo $_SERVER["PHP_SELF"]; // Current script file
echo $_SERVER["SERVER_NAME"]; // Server name
echo $_SERVER["REQUEST_METHOD"]; // Request method (GET/POST)
?>

5. $_FILES (Handles File Uploads)

• Used to upload files in PHP.

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"];
?>

6. $_SESSION (Stores User Data Across Pages)


• Used for storing user information temporarily.

7. $_COOKIE (Stores Small Data on User's Browser)

• Used to store data in the browser.

8. $_ENV (Environment Variables)

• Stores system-level environment variables.


Example:
<?php
echo $_ENV["PATH"]; // Displays system PATH variable
?>

9. $_GLOBALS (Accesses Global Variables in Functions)

• Allows access to global variables inside functions.

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 "Indexed Array:\n";


foreach ($countries as $country) {
echo $country . "<br>";
}
echo "<br>";
// Associative Array
$person = [
"name" => "Alice",
"age" => 25,
"city" => "New York"
];

echo "Associative Array:\n";


foreach ($person as $key => $value) {
echo "$key: $value <br>";
}

echo "<br>";

// Multidimensional Array
$students = [
["id" => 1, "name" => "John", "grade" => "A"],
["id" => 2, "name" => "Emma", "grade" => "B"],
["id" => 3, "name" => "Liam", "grade" => "A"]
];

echo "Multidimensional Array:\n";


foreach ($students as $student) {
echo "ID: " . $student["id"] . ", Name: " . $student["name"] . ", Grade: " . $student["grade"]
. "<br>";
}
?>
OUTPUT
Indexed Array:
USA
UK
Canada
Associative Array:
name: Alice
age: 25
city: New York

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

• You can join strings using the . (dot) operator.


• Example:

<?php

$firstName = "John";

$lastName = "Doe";

$fullName = $firstName . " " . $lastName; // Concatenation

echo $fullName;

?>

3. String Length

Use strlen() to find the length of a string.

<?php

$str = "Hello PHP!";

echo "Length: " . strlen($str);

?>

This returns 11 (including spaces and punctuation).

4. Count Words in a String

Use str_word_count() to count words in a string.

<?php

$str = "Learn PHP programming";

echo "Word Count: " . str_word_count($str);

?>
Output: Word Count: 3

5. Reverse a String

Use strrev() to reverse a string.

<?php

$str = "Hello";

echo strrev($str);

?>

Output: olleH

6. Search for a Word in a String

Use strpos() to find the position of a substring.

7. Replace Words in a String

Use str_replace() to replace words.

<?php

$str = "I love Java";

$newStr = str_replace("Java", "PHP", $str);

echo $newStr;

?>

Output: I love PHP

8. Convert String to Uppercase & Lowercase

• strtoupper() – Converts string to uppercase.


• strtolower() – Converts string to lowercase.

<?php

$str = "Hello World!";

echo strtoupper($str) . "<br>";

echo strtolower($str);

?>
OUTPUT

HELLO WORLD!

hello world!

9. Comparing Strings

Use strcmp() for case-sensitive comparison.

Example:

<?php

$str1 = "Hello";

$str2 = "hello";

if (strcmp($str1, $str2) == 0) {

echo "Strings are equal";

} else {

echo "Strings are not equal";

?>

Output: Strings are not equal

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)

Checking Number Type


1. Check if a variable is an integer (is_int())
<?php
$x = 10;
if (is_int($x)) {
echo "$x is an integer.";
}
?>
Output: 10 is an integer.
2. Check if a variable is a float (is_float())
<?php
$y = 10.5;
if (is_float($y)) {
echo "$y is a float.";
}
?>
🔹 Output: 10.5 is a float.
3. Check if a variable is numeric (is_numeric())
<?php
$z = "100"; // Numeric string
if (is_numeric($z)) {
echo "$z is numeric.";
}
?>
Output: 100 is numeric.
PHP MATH

PHP has built-in functions for mathematical operations.

🔹 Basic Math Functions

1. abs() – Absolute Value

<?php

echo abs(-10); // Output: 10

?>

2. round() – Rounds a Number

<?php

echo round(3.6); // Output: 4

?>

3. ceil() – Rounds Up

<?php

echo ceil(3.1); // Output: 4

?>

4. floor() – Rounds Down

<?php
echo floor(3.9); // Output: 3

?>

BASIC PHP ERRORS

PHP errors occur when something is wrong in the script. Here are the main types of PHP errors:

1. Parse Error (Syntax Error)


Occurs when there is a mistake in syntax, such as missing a semicolon (;) or bracket.
<?php
echo "Hello World" // Missing semicolon
?>
2. Fatal Error
Occurs when a function or class is called but does not exist.
Example:
<?php
undefinedFunction(); // Function not defined
?>
3. Warning
Does not stop script execution but indicates a problem (e.g., missing file).
Example:
<?php
include("nonexistentfile.php"); // File does not exist
?>
4. Deprecated Error
Occurs when using outdated PHP functions.
<?php
split(",", "one,two,three"); // 'split()' is deprecated
?>
Use error_reporting(E_ALL); to show all errors.
Use isset() or empty() to check variables before using them.
Use try...catch for error handling in Fatal Errors.

You might also like