PHP FULL COURSE
What is PHP? PHP Introduction, Uses & Features
1. What is PHP?
PHP stands for Hypertext Preprocessor. It is a popular, open-source, server-side scripting language used to develop dynamic and interactive websites and web applications.
PHP code runs on the web server, and its output is sent to the user's browser in the form of HTML.
PHP is mainly used for backend development, database connectivity, form handling, user authentication, session management, and dynamic web page creation.
PHP can be easily integrated with HTML, CSS, JavaScript, and databases such as MySQL and SQL Server.
Example:
<?php
echo "Hello World!";
?>Output:
Hello World!2. Introduction to PHP
PHP was created by Rasmus Lerdorf in 1994. Initially, PHP was developed to manage personal home pages, but later it became a powerful programming language for web development.
Today, PHP is widely used to build websites, web applications, content management systems, e-commerce websites, and many other online platforms.
PHP is executed on the server, which means users cannot directly see the original PHP source code through their browsers. They only receive the generated output.
How PHP Works
A user opens a PHP-based website in a web browser.
The browser sends a request to the web server.
The web server processes the PHP code.
PHP executes the required operations, such as database queries or calculations.
The server generates HTML output.
The browser displays the result to the user.
3. Uses of PHP
PHP is used for various web development tasks. Some important uses are:
Dynamic Website Development: PHP is used to create dynamic websites where content can change according to user input or database information.
Web Application Development: PHP helps developers build web applications such as management systems, dashboards, and online portals.
Database Connectivity: PHP can connect with databases like MySQL, PostgreSQL, and Microsoft SQL Server to store, retrieve, update, and delete data.
Form Handling: PHP is used to collect and process data submitted through HTML forms.
User Authentication: PHP can be used to develop login, registration, logout, and user verification systems.
Session Management: PHP supports sessions and cookies to maintain user information across multiple web pages.
E-commerce Websites: PHP is used to develop online shopping websites, product management systems, and payment-related applications.
Content Management Systems: PHP is used in popular platforms such as WordPress, Drupal, and Joomla.
File Handling: PHP can create, read, write, upload, and delete files on the server.
API Development: PHP can be used to create REST APIs that allow mobile applications and other systems to communicate with a server.
4. Features of PHP
PHP provides many useful features that make it a popular choice for web development.
Open Source: PHP is free to download, use, and distribute.
Easy to Learn: PHP has a simple syntax that is easy for beginners to understand.
Server-Side Scripting: PHP code executes on the server and generates output for the browser.
Platform Independent: PHP supports different operating systems, including Windows, Linux, and macOS.
Database Support: PHP supports multiple databases, including MySQL, PostgreSQL, SQLite, and Microsoft SQL Server.
Fast Performance: PHP can efficiently execute server-side operations and handle web requests.
HTML Integration: PHP can easily be embedded inside HTML code.
Security: PHP provides features such as password hashing, data filtering, and session management to help developers build secure applications.
Large Community Support: PHP has a large developer community, documentation, libraries, and frameworks.
Framework Support: PHP supports popular frameworks such as Laravel, CodeIgniter, and Symfony.
Object-Oriented Programming: PHP supports classes, objects, inheritance, polymorphism, and encapsulation.
File Handling: PHP provides built-in functions for managing files and directories.
5. Advantages of PHP
Free and open-source programming language.
Easy to learn and implement.
Compatible with multiple operating systems.
Supports different databases.
Easily integrates with HTML.
Suitable for small and large web applications.
Provides many built-in functions.
Supports popular web development frameworks.
6. Disadvantages of PHP
Poorly written PHP code can create security vulnerabilities.
Large applications can become difficult to maintain without proper structure.
Dynamic typing can sometimes cause unexpected errors.
Performance depends on code quality, server configuration, and application architecture.
7. Where is PHP Used?
PHP is used by many popular websites and platforms, including:
WordPress – Content management system.
Wikipedia – Online encyclopedia.
Facebook – Social networking platform (PHP was important in its early development).
Drupal – Content management system.
Joomla – Content management system.
8. Conclusion
PHP is a powerful, flexible, and widely used server-side programming language. It allows developers to create dynamic websites, web applications, database-driven systems, APIs, and content management systems.
Because PHP is free, easy to learn, and supports multiple databases and frameworks, it is a good choice for beginners who want to start learning backend web development.
In simple words: PHP is a server-side programming language that helps us make dynamic and database-driven websites.
How to Install XAMPP and Set Up PHP on Windows
1. What is XAMPP?
XAMPP is a free and open-source software package used to create a local web development environment on a computer.
It allows developers to run PHP applications and test websites locally without purchasing web hosting or uploading files to a live server.
XAMPP includes the following components:
Apache: A web server used to execute PHP files and serve web pages.
MySQL/MariaDB: A database management system used to store and manage application data.
PHP: A server-side programming language used to develop dynamic websites.
Perl: A programming language included with XAMPP.
phpMyAdmin: A web-based tool used to manage databases.
2. Requirements for PHP Development
Before starting PHP development, we need the following:
Windows operating system.
XAMPP software.
A code editor such as Visual Studio Code.
A web browser such as Google Chrome.
3. How to Download XAMPP
Follow these steps to download XAMPP:
Open Google Chrome.
Search for XAMPP Download.
Open the official Apache Friends website.
Select the XAMPP version compatible with your Windows operating system.
Download the installer.
Wait until the download is completed.
Official Website: https://www.apachefriends.org/
4. How to Install XAMPP
Follow these steps to install XAMPP:
Open the downloaded XAMPP installer.
Click on the Yes button if Windows asks for permission.
Click on Next.
Select the components you want to install, such as Apache, MySQL, PHP, and phpMyAdmin.
Select the installation directory. By default, it is
C:\xampp.Click Next and continue the installation.
Wait for the installation process to complete.
Click Finish to launch the XAMPP Control Panel.
5. How to Start Apache Server
After installing XAMPP, follow these steps:
Open the XAMPP Control Panel.
Find the Apache module.
Click on the Start button.
Wait until Apache turns green.
Apache is now running successfully.
Apache is responsible for processing PHP requests and displaying PHP output in the browser.
6. How to Create Your First PHP Project
Follow these steps:
Step 1: Open the XAMPP installation folder.
Step 2: Open the htdocs folder.
Default location:
C:\xampp\htdocsStep 3: Create a new folder named:
PHP_TutorialStep 4: Open the PHP_Tutorial folder in Visual Studio Code.
Step 5: Create a new file named:
index.phpStep 6: Write the following PHP code:
<?php
echo "Hello World!";
?>Step 7: Save the file.
7. How to Run PHP Code in the Browser
Follow these steps:
Make sure Apache is running in the XAMPP Control Panel.
Open Google Chrome.
Enter the following URL:
http://localhost/PHP_Tutorial/4. Press Enter.
Output:
Hello World!Congratulations! Your first PHP program is running successfully on your local server.
8. What is Localhost?
Localhost refers to the current computer on which a web server is running.
In PHP development, localhost is commonly used to access websites and applications stored inside the XAMPP htdocs folder.
For example:
http://localhost/It is commonly associated with the IP address:
127.0.0.19. What is the htdocs Folder?
The htdocs folder is the default document root directory of Apache in XAMPP.
It is used to store PHP projects, HTML files, CSS files, JavaScript files, and other website resources.
Example:
C:\xampp\htdocs\
PHP_Tutorial/
index.php
MyWebsite/
index.php
Student_Management/
index.phpTo access these projects, use:
http://localhost/PHP_Tutorial/
http://localhost/MyWebsite/
http://localhost/Student_Management/10. Conclusion
XAMPP makes PHP development easy by providing a local server environment on our computer. Using XAMPP, we can execute PHP programs, create websites, connect databases, and test web applications without requiring a live hosting server.
By installing XAMPP and running our first PHP program, we have successfully completed the basic PHP development setup.
PHP Syntax – PHP Tags, Statements, Comments and Basic Rules
1. What is PHP Syntax?
PHP syntax refers to the set of rules and guidelines that we must follow when writing PHP code.
These rules help PHP understand and execute instructions correctly.
PHP code is generally written inside PHP tags, and every PHP statement usually ends with a semicolon (;).
Example:
<?php
echo "Hello World!";
?>Output:
Hello World!2. PHP Opening and Closing Tags
PHP code is written between opening and closing PHP tags.
Opening tag:
<?phpClosing tag:
?>
The opening tag tells the server where PHP code begins, and the closing tag indicates where PHP code ends.
Example:
<?php
echo "Welcome to PHP Programming";
?>Output:
Welcome to PHP ProgrammingWe can also write HTML and PHP together in the same file.
Example:
<!DOCTYPE html>
<html>
<head>
<title>PHP Tutorial</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<?php
echo "Hello, PHP!";
?>
</body>
</html>3. PHP Statements
A statement is an instruction given to PHP to perform a particular task.
In PHP, most statements end with a semicolon (;).
Example:
<?php
echo "Hello World!";
echo "Welcome to PHP";
echo 100 + 200;
?>Output:
Hello World!Welcome to PHP300Here, each echo is a PHP statement.
4. PHP Comments
Comments are used to explain PHP code. They are ignored by the PHP interpreter and are not executed.
PHP supports three types of comments.
A. Single-Line Comment
A single-line comment is used to write a comment on one line.
We can use two symbols:
//#
Example:
<?php
// This is a single-line comment
echo "Hello World!";
# This is also a single-line comment
?>Output:
Hello World!B. Multi-Line Comment
A multi-line comment is used when we want to write comments across multiple lines.
We use /* to start a comment and */ to end it.
Example:
<?php
/*
This is a multi-line comment.
We can write multiple lines here.
PHP will ignore these comments.
*/
echo "Welcome to PHP";
?>Output:
Welcome to PHP5. PHP Case Sensitivity
PHP has different case-sensitivity rules depending on the type of element.
A. Keywords and Language Constructs
PHP keywords and language constructs are case-insensitive.
For example, echo, ECHO, and Echo work.
Example:
<?php
echo "Hello";
ECHO " World";
Echo " PHP";
?>Output:
Hello World PHPB. Variable Names
PHP variable names are case-sensitive.
For example, $name, $Name, and $NAME are treated as three different variables.
Example:
<?php
$name = "Rehan";
$Name = "Khan";
echo $name;
echo "<br>";
echo $Name;
?>Output:
Rehan
Khan6. PHP White Spaces
White spaces include spaces, tabs, and line breaks.
PHP generally ignores unnecessary white spaces between statements, so we can write code in a readable format.
Example:
<?php
$name = "Rehan";
echo $name;
?>The same code can also be written as:
<?php $name="Rehan"; echo $name; ?>Output:
RehanHowever, writing code with proper spacing and indentation makes it easier to understand and maintain.
7. PHP Rules for Writing Variables
PHP variables are used to store data.
Some important rules for creating variables are:
Every PHP variable starts with a dollar sign (
$).A variable name must start with a letter or underscore (
_).A variable name cannot start with a number.
A variable name can contain letters, numbers, and underscores.
Variable names are case-sensitive.
Variable names cannot contain spaces.
Valid Variable Names:
$name = "Rehan";
$age = 25;
$_city = "Delhi";
$student_name = "Rahul";Invalid Variable Names:
$1name = "Rehan";
$student name = "Rahul";
$my-name = "Delhi";8. PHP Echo Statement
The echo statement is used to display output on a web page.
It can display text, variables, and HTML elements.
Example:
<?php
echo "Hello World!";
echo "<br>";
echo "Welcome to LearnWithRehan";
?>Output:
Hello World!
Welcome to LearnWithRehan9. PHP Print Statement
The print statement is also used to display output on a web page.
Both echo and print are language constructs, but there is a small difference:
echocan accept multiple comma-separated arguments.printaccepts one argument and returns the value1.
Example:
<?php
echo "Hello ", "World!";
echo "<br>";
print "Welcome to PHP";
?>Output:
Hello World!
Welcome to PHP10. Difference Between Echo and Print in PHP
Echo | |
|---|---|
Used to display output. | Used to display output. |
Can accept multiple arguments. | Accepts one argument. |
Does not return a value. | Returns 1. |
Generally slightly simpler for output. | Can be used in expressions because it returns 1. |
11. PHP Syntax Best Practices
Always write clean and readable code.
Use proper indentation.
Use meaningful variable names.
Add comments wherever necessary.
Use semicolons after PHP statements.
Use consistent naming conventions.
Avoid unnecessary closing PHP tags in files containing only PHP code, as accidental trailing whitespace can cause problems.
12. Conclusion
PHP syntax defines the rules for writing PHP programs. We use PHP opening and closing tags to write PHP code, semicolons to terminate statements, and comments to explain our code.
Understanding PHP syntax, statements, comments, and basic rules is essential before moving to advanced PHP programming.
PHP Variables – How to Declare, Initialize and Display Variables in PHP
1. What is a Variable in PHP?
A variable in PHP is a named memory location used to store data such as numbers, strings, decimal values, and other types of information.
Variables allow us to store data and use or modify it whenever required in a program.
In PHP, every variable starts with a dollar sign ($).
Example:
<?php
$name = "Rehan";
$age = 25;
echo $name;
echo "<br>";
echo $age;
?>Output:
Rehan
25Here:
$nameis a variable that stores the valueRehan.$ageis a variable that stores the value25.
2. How to Declare a Variable in PHP?
In PHP, we do not need to specify the data type while declaring a variable.
We simply write the dollar sign ($), followed by the variable name and an assignment operator (=).
Syntax:
$variable_name = value;Example:
<?php
$name = "Rahul";
$age = 22;
$salary = 25000.50;
echo $name;
echo "<br>";
echo $age;
echo "<br>";
echo $salary;
?>Output:
Rahul
22
25000.53. Rules for Naming Variables in PHP
There are some important rules that we must follow when creating PHP variables.
Every variable must start with a dollar sign (
$).A variable name must start with a letter or underscore (
_).A variable name cannot start with a number.
A variable name can contain letters, numbers, and underscores.
Variable names are case-sensitive.
Variable names cannot contain spaces.
Special characters are not allowed in variable names except underscore.
Valid Variable Names:
$name = "Rehan";
$age = 25;
$_city = "Delhi";
$student_name = "Rahul";
$salary2026 = 30000;Invalid Variable Names:
$1name = "Rehan";
$student name = "Rahul";
$my-name = "Delhi";
$@salary = 25000;4. Types of Values Stored in PHP Variables
PHP is a dynamically typed language. This means we do not need to declare the data type of a variable explicitly. PHP automatically determines the data type based on the assigned value.
We can store different types of values in PHP variables.
A. String
A string is a sequence of characters enclosed in single or double quotation marks.
Example:
<?php
$name = "Rehan Khan";
echo $name;
?>Output:
Rehan KhanB. Integer
An integer is a whole number without a decimal point.
Example:
<?php
$age = 25;
echo $age;
?>Output:
25C. Float
A float is a number that contains a decimal point.
Example:
<?php
$price = 250.75;
echo $price;
?>Output:
250.75D. Boolean
A Boolean variable stores either true or false.
Example:
<?php
$isActive = true;
$isLogin = false;
var_dump($isActive);
echo "<br>";
var_dump($isLogin);
?>Output:
bool(true)
bool(false)E. Array
An array is used to store multiple values in a single variable.
Example:
<?php
$fruits = array("Apple", "Mango", "Banana");
echo $fruits[0];
?>Output:
AppleF. NULL
NULL represents a variable that has no value.
Example:
<?php
$name = NULL;
var_dump($name);
?>Output:
NULL5. How to Display Variables in PHP?
We can use echo, print, and var_dump() to display variable values.
Example:
<?php
$name = "Rehan";
$age = 25;
echo $name;
echo "<br>";
print $age;
echo "<br>";
var_dump($name);
?>Output:
Rehan
25
string(5) "Rehan"echodisplays the variable value.printdisplays the variable value.var_dump()displays the value along with its data type and additional information.
6. PHP Variables Are Case-Sensitive
PHP variable names are case-sensitive. This means $name, $Name, and $NAME are three different variables.
Example:
<?php
$name = "Rehan";
$Name = "Rahul";
$NAME = "Amit";
echo $name;
echo "<br>";
echo $Name;
echo "<br>";
echo $NAME;
?>Output:
Rehan
Rahul
Amit7. Assigning Values to Variables
We can assign values to variables using the assignment operator (=).
We can also change the value of a variable whenever required.
Example:
<?php
$name = "Rehan";
echo $name;
echo "<br>";
$name = "Khan";
echo $name;
?>Output:
Rehan
KhanHere, initially the variable $name contains Rehan. Later, we change its value to Khan.
8. PHP Variables Without Specifying Data Types
In PHP, we do not need to specify the data type while creating a variable.
PHP automatically identifies the data type based on the assigned value.
Example:
<?php
$data = "Hello";
var_dump($data);
echo "<br>";
$data = 100;
var_dump($data);
echo "<br>";
$data = 100.50;
var_dump($data);
?>Output:
string(5) "Hello"
int(100)
float(100.5)Here, the same variable $data stores a string, an integer, and a float value at different times.
9. PHP Variable Scope
Variable scope defines where a variable can be accessed in a PHP program.
PHP mainly supports four types of variable scope:
Local Variable: A variable declared inside a function is called a local variable. It can normally be accessed only inside that function.
Global Variable: A variable declared outside a function is called a global variable. To access it inside a function, we can use the
globalkeyword or the$GLOBALSarray.Static Variable: A static variable retains its value between function calls.
Parameter Variable: A variable passed to a function as an argument is called a parameter.
Example of Local and Global Variables:
<?php
$name = "Rehan"; // Global variable
function displayName()
{
$age = 25; // Local variable
echo "Age: " . $age;
}
echo "Name: " . $name;
echo "<br>";
displayName();
?>Output:
Name: Rehan
Age: 2510. Advantages of Variables in PHP
Variables help us store and manage data.
We can reuse stored values multiple times.
Variables make programs dynamic and flexible.
We can update variable values whenever required.
Variables help us perform mathematical calculations.
Variables make code easier to understand and maintain.
11. Conclusion
Variables are one of the most important concepts in PHP programming. They allow us to store different types of data and use that data throughout our programs.
In PHP, variables start with a dollar sign ($), and we do not need to specify their data types explicitly because PHP automatically determines the type of value.
Understanding variables, naming rules, data types, and variable scope is essential for learning PHP programming.
PHP Data Types – All 8 Data Types in PHP with Examples
1. What are Data Types in PHP?
Data types define the type of data that a variable can store in a PHP program.
For example, if we want to store a person's name, we use a String data type. If we want to store age, we use an Integer data type. Similarly, PHP provides different data types to store different kinds of information.
PHP is a dynamically typed language, which means we do not need to specify the data type explicitly when declaring a variable. PHP automatically determines the data type based on the assigned value.
PHP supports the following 8 major data types:
String
Integer
Float (Double)
Boolean
Array
Object
NULL
Resource
Let's understand each data type with examples.
2. String Data Type
A String is a sequence of characters used to store text, such as names, addresses, messages, and other textual information.
In PHP, strings can be written using single quotes (' ') or double quotes (" ").
Example:
<?php
$name = "Rehan Khan";
$city = 'Delhi';
echo $name;
echo "<br>";
echo $city;
?>Output:
Rehan Khan
DelhiHere, $name and $city are string variables because they contain text values.
3. Integer Data Type
An Integer is a whole number without a decimal point.
Integers can be positive numbers, negative numbers, or zero.
Example:
<?php
$age = 25;
$salary = 30000;
$temperature = -10;
echo $age;
echo "<br>";
echo $salary;
echo "<br>";
echo $temperature;
?>Output:
25
30000
-10Here, all three variables contain integer values.
4. Float Data Type
A Float is a numeric value that contains a decimal point.
It is used to store values such as prices, percentages, measurements, and other decimal numbers.
PHP also uses the term Double for floating-point values.
Example:
<?php
$price = 250.75;
$percentage = 85.50;
$temperature = -5.25;
echo $price;
echo "<br>";
echo $percentage;
echo "<br>";
echo $temperature;
?>Output:
250.75
85.5
-5.25Here, all variables contain floating-point values.
5. Boolean Data Type
A Boolean data type represents only two possible values:
TRUE
FALSE
It is commonly used in decision-making, conditions, login systems, and checking whether a particular condition is satisfied.
Example:
<?php
$isLogin = true;
$isActive = false;
var_dump($isLogin);
echo "<br>";
var_dump($isActive);
?>Output:
bool(true)
bool(false)Here, $isLogin contains TRUE, and $isActive contains FALSE.
6. Array Data Type
An Array is used to store multiple values in a single variable.
Instead of creating separate variables for every value, we can store multiple values inside one array.
PHP supports three main types of arrays:
A. Indexed Array
An Indexed Array stores values using numeric indexes. By default, indexing starts from zero.
Example:
<?php
$fruits = array("Apple", "Mango", "Banana");
echo $fruits[0];
echo "<br>";
echo $fruits[1];
echo "<br>";
echo $fruits[2];
?>Output:
Apple
Mango
BananaB. Associative Array
An Associative Array stores values using named keys instead of numeric indexes.
Example:
<?php
$student = array(
"name" => "Rehan",
"age" => 25,
"city" => "Delhi"
);
echo $student["name"];
echo "<br>";
echo $student["age"];
echo "<br>";
echo $student["city"];
?>Output:
Rehan
25
DelhiC. Multidimensional Array
A Multidimensional Array is an array that contains one or more arrays inside it.
Example:
<?php
$students = array(
array("Rehan", 25, "Delhi"),
array("Rahul", 22, "Mumbai"),
array("Amit", 24, "Pune")
);
echo $students[0][0];
echo "<br>";
echo $students[1][0];
echo "<br>";
echo $students[2][0];
?>Output:
Rehan
Rahul
Amit7. Object Data Type
An Object is an instance of a class.
Objects are used in Object-Oriented Programming (OOP) to combine data and functions into a single unit.
To create an object in PHP, we first define a class and then create an object using the new keyword.
Example:
<?php
class Student
{
public $name = "Rehan";
public $age = 25;
public function display()
{
echo "Name: " . $this->name;
echo "<br>";
echo "Age: " . $this->age;
}
}
$student = new Student();
$student->display();
?>Output:
Name: Rehan
Age: 25Here:
Studentis a class.$studentis an object.newis used to create an object.$thisrefers to the current object.
8. NULL Data Type
NULL is a special data type that represents a variable with no value.
When a variable is assigned NULL, it means that the variable does not contain any value.
Example:
<?php
$name = NULL;
var_dump($name);
?>Output:
NULLWe can also assign NULL to an existing variable.
Example:
<?php
$name = "Rehan";
$name = NULL;
var_dump($name);
?>Output:
NULL9. Resource Data Type
A Resource is a special variable that holds a reference to an external resource, such as a file handle or database connection.
Resources are commonly used when working with files, database connections, and other external services.
Example:
<?php
$file = fopen("test.txt", "w");
var_dump($file);
fclose($file);
?>Output:
resource(...)The exact resource identifier may vary depending on the PHP environment.
Here:
fopen()opens a file.$filestores the file resource.var_dump()displays the resource information.fclose()closes the file.
10. How to Check Data Types in PHP?
PHP provides different functions to check and display the data type of a variable.
Some commonly used functions are:
Function | Description |
|---|---|
| Returns the data type of a variable as a string. |
| Displays the data type and value of a variable. |
| Checks whether a variable is a string. |
| Checks whether a variable is an integer. |
| Checks whether a variable is a float. |
| Checks whether a variable is a Boolean. |
| Checks whether a variable is an array. |
| Checks whether a variable is an object. |
| Checks whether a variable is NULL. |
Example:
<?php
$name = "Rehan";
$age = 25;
$salary = 25000.50;
echo gettype($name);
echo "<br>";
echo gettype($age);
echo "<br>";
echo gettype($salary);
?>Output:
string
integer
doubleNote: PHP's gettype() function returns integer for integers and double for floating-point values.
11. Difference Between PHP Data Types
Data Type | Description | Example |
|---|---|---|
String | Stores text |
|
Integer | Stores whole numbers |
|
Float | Stores decimal numbers |
|
Boolean | Stores TRUE or FALSE |
|
Array | Stores multiple values |
|
Object | Stores class instances |
|
NULL | Represents no value |
|
Resource | Holds external resource references |
|
12. Advantages of PHP Data Types
Data types help organize different kinds of information.
They make data handling easier.
They support mathematical calculations.
They help developers work with strings, arrays, and objects.
They make database operations easier.
They support decision-making using Boolean values.
They help developers build dynamic web applications.
13. Conclusion
PHP provides eight major data types: String, Integer, Float, Boolean, Array, Object, NULL, and Resource.
Each data type is used for storing and managing different kinds of information. Understanding PHP data types is important because they are used in almost every PHP application, including websites, APIs, database systems, and web applications.
PHP Constants – How to Create and Use Constants in PHP
1. What is a Constant in PHP?
A Constant in PHP is a name or identifier used to store a value that cannot be changed once it has been defined.
Unlike variables, constants do not use the dollar sign ($) before their names.
Constants are useful when we want to store fixed values that remain the same throughout the execution of a program.
For example:
Website name
Website URL
Company name
Database configuration values
Application version
Example:
<?php
define("SITE_NAME", "LearnWithRehan");
echo SITE_NAME;
?>Output:
LearnWithRehanHere, SITE_NAME is a constant that stores the value LearnWithRehan.
2. Features of PHP Constants
Some important features of PHP constants are:
Constants store fixed values.
Constants do not use the dollar sign (
$).Constants cannot be changed or redefined once successfully defined.
Constants are globally accessible within their PHP execution scope.
Constants can store different types of values.
Constants are case-sensitive by default.
Constants can be created using
define()orconst.
3. How to Create Constants Using define()
PHP provides the define() function to create constants.
The define() function is used to define a constant with a name and value.
Syntax:
define("CONSTANT_NAME", value);Here:
define()is a PHP function.CONSTANT_NAMEis the name of the constant.valueis the value assigned to the constant.
Example:
<?php
define("PI", 3.14159);
define("WEBSITE", "LearnWithRehan");
echo PI;
echo "<br>";
echo WEBSITE;
?>Output:
3.14159
LearnWithRehan4. How to Create Constants Using const Keyword
PHP also provides the const keyword to create constants.
It allows us to declare a constant directly without using the define() function.
Syntax:
const CONSTANT_NAME = value;Example:
<?php
const SITE_NAME = "LearnWithRehan";
const VERSION = "1.0";
echo SITE_NAME;
echo "<br>";
echo VERSION;
?>Output:
LearnWithRehan
1.05. Difference Between define() and const in PHP
Both define() and const are used to create constants, but there are some differences.
define() | const |
|---|---|
It is a PHP function. | It is a PHP language keyword. |
Constants are created at runtime. | Constants are declared at compile time. |
Can be used inside conditional blocks and functions. | Cannot be declared inside functions or conditional blocks. |
Supports dynamically calculated constant names. | Constant names must be written directly in the declaration. |
Used to define constants dynamically. | Used for straightforward constant declarations. |
Example of define() Inside a Condition:
<?php
if (true) {
define("APP_NAME", "LearnWithRehan");
}
echo APP_NAME;
?>Output:
LearnWithRehanNote: const declarations are not allowed inside conditional blocks or functions.
6. PHP Constants Are Case-Sensitive
By default, PHP constants are case-sensitive.
This means SITE_NAME and site_name are treated as two different constant names.
Example:
<?php
define("SITE_NAME", "LearnWithRehan");
define("site_name", "PHP Tutorial");
echo SITE_NAME;
echo "<br>";
echo site_name;
?>Output:
LearnWithRehan
PHP Tutorial7. PHP Constants Cannot Be Changed
Once a constant is defined, its value cannot be changed or redefined.
Example:
<?php
define("COLLEGE", "ABC College");
echo COLLEGE;
echo "<br>";
// Attempting to change the constant
define("COLLEGE", "XYZ College");
echo COLLEGE;
?>Output:
ABC College
ABC CollegeThe second define() call produces a warning because the constant is already defined. Its original value remains unchanged.
8. PHP Constants Can Store Different Data Types
PHP constants are not limited to strings or numbers. They can store different data types.
For example:
String Constant:
<?php
define("NAME", "Rehan");
echo NAME;
?>Output:
RehanInteger Constant:
<?php
define("AGE", 25);
echo AGE;
?>Output:
25Float Constant:
<?php
define("PRICE", 250.50);
echo PRICE;
?>Output:
250.5Boolean Constant:
<?php
define("STATUS", true);
var_dump(STATUS);
?>Output:
bool(true)Array Constant:
<?php
define("FRUITS", ["Apple", "Mango", "Banana"]);
echo FRUITS[0];
echo "<br>";
echo FRUITS[1];
?>Output:
Apple
Mango9. PHP Magic Constants
PHP also provides special predefined constants called Magic Constants.
These constants automatically return information depending on where they are used in the code.
Some commonly used magic constants are:
Magic Constant | Description |
|---|---|
| Returns the current line number of the file. |
| Returns the full path and filename of the current file. |
| Returns the directory of the current file. |
| Returns the current function name. |
| Returns the current class name. |
| Returns the current class method name. |
| Returns the current namespace name. |
| Returns the current trait name. |
Example:
<?php
echo "Current Line: " . __LINE__;
echo "<br>";
echo "File Name: " . __FILE__;
echo "<br>";
echo "Directory: " . __DIR__;
?>Output:
Current Line: 3
File Name: C:\xampp\htdocs\PHP_Tutorial\index.php
Directory: C:\xampp\htdocs\PHP_TutorialThe file path and line numbers will depend on your project location and code.
10. Difference Between Variables and Constants in PHP
Variables | Constants |
|---|---|
Variables are used to store data that can change. | Constants are used to store fixed values. |
Variables start with | Constants do not use |
Variables are case-sensitive. | Constants are case-sensitive by default. |
Variables can be reassigned. | Constants cannot be reassigned. |
Variables are declared using | Constants are created using |
Variables have local, global, and static scope rules. | User-defined constants are globally accessible. |
Example:
<?php
$name = "Rehan";
define("SITE_NAME", "LearnWithRehan");
// Changing variable value
$name = "Rahul";
echo $name;
echo "<br>";
echo SITE_NAME;
?>Output:
Rahul
LearnWithRehan11. Advantages of Constants in PHP
Constants help store fixed values.
They prevent accidental reassignment.
They make programs easier to maintain.
They improve code readability.
They are useful for storing application configuration values.
They can be accessed globally within the PHP execution scope.
12. Conclusion
Constants are an important concept in PHP programming. They are used to store fixed values that should not change during program execution.
PHP provides two main ways to create constants: the define() function and the const keyword.
Understanding constants helps developers write organized, readable, and maintainable PHP applications.
PHP Operators – Types of Operators in PHP with Examples
1. What are Operators in PHP?
Operators in PHP are special symbols or keywords used to perform operations on variables and values.
Operators help us perform mathematical calculations, compare values, assign values, and make logical decisions in a PHP program.
For example, if we want to add two numbers, we use the addition operator (+). If we want to compare two values, we use comparison operators such as (==) or (>).
Example:
<?php
$a = 10;
$b = 20;
$result = $a + $b;
echo "Addition: " . $result;
?>Output:
Addition: 30Here:
$aand$bare variables.+is an arithmetic operator.$resultstores the addition result.
2. Types of Operators in PHP
PHP provides different types of operators to perform various operations.
The main types of PHP operators are:
Arithmetic Operators
Assignment Operators
Comparison Operators
Increment and Decrement Operators
Logical Operators
String Operators
Array Operators
Conditional (Ternary) Operator
Null Coalescing Operator
Bitwise Operators
Type Operator
Let's understand each operator with examples.
3. Arithmetic Operators in PHP
Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, and division.
Operator | Name | Description |
|---|---|---|
| Addition | Adds two values. |
| Subtraction | Subtracts one value from another. |
| Multiplication | Multiplies two values. |
| Division | Divides one value by another. |
| Modulus | Returns the remainder. |
| Exponentiation | Calculates the power of a number. |
Example:
<?php
$a = 20;
$b = 10;
echo "Addition: " . ($a + $b);
echo "<br>";
echo "Subtraction: " . ($a - $b);
echo "<br>";
echo "Multiplication: " . ($a * $b);
echo "<br>";
echo "Division: " . ($a / $b);
echo "<br>";
echo "Modulus: " . ($a % $b);
echo "<br>";
echo "Exponentiation: " . ($a ** 2);
?>Output:
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Modulus: 0
Exponentiation: 4004. Assignment Operators in PHP
Assignment operators are used to assign values to variables.
The basic assignment operator is (=). PHP also provides compound assignment operators that perform an operation and assign the result to the same variable.
Operator | Example | Equivalent Expression |
|---|---|---|
|
| Assigns 10 to |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| Concatenates and assigns a string. |
Example:
<?php
$a = 10;
$a += 5;
echo "Addition: " . $a;
echo "<br>";
$a -= 3;
echo "Subtraction: " . $a;
echo "<br>";
$a *= 2;
echo "Multiplication: " . $a;
?>Output:
Addition: 15
Subtraction: 12
Multiplication: 245. Comparison Operators in PHP
Comparison operators are used to compare two values.
They return a Boolean result, either TRUE or FALSE.
Operator | Name | Description |
|---|---|---|
| Equal | Checks whether two values are equal after type conversion if necessary. |
| Identical | Checks whether values and data types are equal. |
| Not Equal | Checks whether two values are not equal. |
| Not Equal | Another way to check inequality. |
| Not Identical | Checks whether values or data types are different. |
| Greater Than | Checks whether the left value is greater. |
| Less Than | Checks whether the left value is smaller. |
| Greater Than or Equal | Checks whether the left value is greater than or equal to the right. |
| Less Than or Equal | Checks whether the left value is smaller than or equal to the right. |
| Spaceship | Returns -1, 0, or 1 depending on the comparison. |
Example:
<?php
$a = 10;
$b = 20;
var_dump($a == $b);
echo "<br>";
var_dump($a != $b);
echo "<br>";
var_dump($a > $b);
echo "<br>";
var_dump($a < $b);
echo "<br>";
var_dump($a <= $b);
?>Output:
bool(false)
bool(true)
bool(false)
bool(true)
bool(true)Difference Between == and ===
The == operator checks whether two values are equal, while the === operator checks both the value and data type.
Example:
<?php
$a = 10;
$b = "10";
var_dump($a == $b);
echo "<br>";
var_dump($a === $b);
?>Output:
bool(true)
bool(false)Here, both variables have the same value, but their data types are different. Therefore, == returns TRUE and === returns FALSE.
6. Increment and Decrement Operators in PHP
Increment and decrement operators are used to increase or decrease the value of a variable by one.
Operator | Name | Description |
|---|---|---|
| Pre-Increment | Increases the value first, then returns it. |
| Post-Increment | Returns the current value first, then increases it. |
| Pre-Decrement | Decreases the value first, then returns it. |
| Post-Decrement | Returns the current value first, then decreases it. |
Example:
<?php
$a = 10;
echo ++$a;
echo "<br>";
echo $a++;
echo "<br>";
echo $a;
echo "<br>";
echo --$a;
echo "<br>";
echo $a--;
echo "<br>";
echo $a;
?>Output:
11
11
12
11
11
107. Logical Operators in PHP
Logical operators are used to combine multiple conditions.
They are commonly used in if, else, and other conditional statements.
| Operator | Name | Description |
|---|---|---|
| && | Logical AND | TRUE if both conditions are TRUE. |
| || | Logical OR | TRUE if at least one condition is TRUE. |
| ! | Logical NOT | Reverses the Boolean result. |
| and | Logical AND | Another form of AND. |
| or | Logical OR | Another form of OR. |
| xor | Logical XOR | TRUE if exactly one condition is TRUE. |
Example:
<?php
$a = 10;
$b = 20;
var_dump($a < 20 && $b > 10);
echo "<br>";
var_dump($a > 20 || $b > 10);
echo "<br>";
var_dump(!($a > 20));
echo "<br>";
var_dump(($a < 20) xor ($b < 10));
?>Output:
bool(true)
bool(true)
bool(true)
bool(true)8. String Operators in PHP
String operators are used to combine strings or concatenate string values.
PHP provides two main string operators.
Operator | Name | Description |
|---|---|---|
| Concatenation | Combines two strings. |
| Concatenation Assignment | Combines a string with a variable and assigns the result. |
Example:
<?php
$firstName = "Rehan";
$lastName = "Khan";
$fullName = $firstName . " " . $lastName;
echo $fullName;
echo "<br>";
$fullName .= " - LearnWithRehan";
echo $fullName;
?>Output:
Rehan Khan
Rehan Khan - LearnWithRehan9. Array Operators in PHP
Array operators are used to compare or combine arrays.
Operator | Name | Description |
|---|---|---|
| Union | Combines two arrays. Keys from the left array take priority when keys are duplicated. |
| Equality | Checks whether two arrays have the same key-value pairs. |
| Identity | Checks whether arrays have the same key-value pairs, in the same order, with the same data types. |
| Inequality | Checks whether two arrays are not equal. |
| Inequality | Another way to check array inequality. |
| Non-Identity | Checks whether arrays are not identical. |
Example:
<?php
$array1 = array("a" => "Apple", "b" => "Banana");
$array2 = array("c" => "Mango", "d" => "Orange");
$result = $array1 + $array2;
print_r($result);
?>Output:
Array
(
[a] => Apple
[b] => Banana
[c] => Mango
[d] => Orange
)10. Conditional (Ternary) Operator in PHP
The Ternary Operator is a shorthand way of writing a simple if-else condition.
It uses three operands: a condition, a value if TRUE, and a value if FALSE.
Syntax:
condition ? value_if_true : value_if_false;Example:
<?php
$age = 20;
$result = ($age >= 18) ? "Eligible to Vote" : "Not Eligible to Vote";
echo $result;
?>Output:
Eligible to VoteHere, if the age is 18 or above, the result will be Eligible to Vote; otherwise, it will be Not Eligible to Vote.
11. Null Coalescing Operator in PHP
The Null Coalescing Operator (??) is used to check whether a variable exists and is not NULL.
If the variable exists and is not NULL, it returns its value. Otherwise, it returns the alternative value.
Example:
<?php
$name = NULL;
$result = $name ?? "Guest";
echo $result;
?>Output:
GuestHere, $name contains NULL, so the operator returns Guest.
12. Bitwise Operators in PHP
Bitwise operators are used to perform operations on the individual bits of integer values.
| Operator | Name | Description |
|---|---|---|
| & | AND | Performs bitwise AND. |
| | | OR | Performs bitwise OR. |
| ^ | XOR | Performs bitwise XOR. |
| ~ | NOT | Inverts the bits. |
| << | Left Shift | Shifts bits to the left. |
| >> | Right Shift | Shifts bits to the right. |
Example:
<?php
$a = 5;
$b = 3;
echo $a & $b;
echo "<br>";
echo $a | $b;
echo "<br>";
echo $a ^ $b;
?>Output:
1
7
613. Type Operator in PHP
PHP provides the instanceof operator to check whether an object belongs to a particular class or is an instance of a particular class or its compatible type.
Example:
<?php
class Student
{
}
$obj = new Student();
var_dump($obj instanceof Student);
?>Output:
bool(true)Here, $obj is an object of the Student class, so the instanceof operator returns TRUE.
14. Advantages of PHP Operators
Operators make mathematical calculations easy.
They help compare different values.
They allow developers to perform logical operations.
They make conditional statements easier.
They help combine strings and arrays.
They make PHP programs more dynamic and flexible.
15. Conclusion
PHP operators are an important part of PHP programming. They help us perform mathematical calculations, assign values, compare data, combine conditions, and manipulate strings and arrays.
Understanding different types of operators is essential because operators are used in almost every PHP program and web application.
PHP Conditional Statements – If, If-Else, Elseif, Nested If and Switch Statements
1. What are Conditional Statements in PHP?
Conditional statements in PHP are used to execute different blocks of code based on specific conditions.
They help a program make decisions depending on whether a condition is TRUE or FALSE.
For example, if we want to check whether a person is eligible to vote, we can use a conditional statement to check whether their age is 18 or above.
PHP provides the following conditional statements:
If Statement
If-Else Statement
If-Elseif-Else Statement
Nested If Statement
Switch Statement
Match Expression
Let's understand each conditional statement with examples.
2. PHP If Statement
The if statement is used to execute a block of code only when a given condition is TRUE.
If the condition is FALSE, the code inside the if block will not execute.
Syntax:
if (condition) {
// Code to execute if condition is TRUE
}Example:
<?php
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
?>Output:
You are eligible to vote.Here, the age is 20, which is greater than 18. Therefore, the condition is TRUE, and the code inside the if block executes.
3. PHP If-Else Statement
The if-else statement is used when we want to execute one block of code if the condition is TRUE and another block if the condition is FALSE.
Syntax:
if (condition) {
// Code if condition is TRUE
} else {
// Code if condition is FALSE
}Example:
<?php
$age = 16;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
?>Output:
You are not eligible to vote.Here, the age is 16, so the condition is FALSE. Therefore, the else block executes.
4. PHP If-Elseif-Else Statement
The if-elseif-else statement is used when we need to check multiple conditions in a program.
PHP checks the conditions from top to bottom. When a condition becomes TRUE, its corresponding block executes, and the remaining conditions are skipped.
Syntax:
if (condition1) {
// Code if condition1 is TRUE
} elseif (condition2) {
// Code if condition2 is TRUE
} else {
// Code if all conditions are FALSE
}Example:
<?php
$marks = 75;
if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 75) {
echo "Grade B";
} elseif ($marks >= 60) {
echo "Grade C";
} elseif ($marks >= 40) {
echo "Grade D";
} else {
echo "Fail";
}
?>Output:
Grade BHere, the marks are 75, so the second condition is TRUE, and the output will be Grade B.
5. PHP Nested If Statement
A Nested If Statement means writing one if statement inside another if statement.
It is useful when we want to check an additional condition only after the first condition is TRUE.
Syntax:
if (condition1) {
if (condition2) {
// Code if both conditions are TRUE
}
}Example:
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18) {
if ($hasLicense == true) {
echo "You are eligible to drive.";
} else {
echo "You need a driving license.";
}
} else {
echo "You are not eligible to drive.";
}
?>Output:
You are eligible to drive.Here:
First, PHP checks whether the age is 18 or above.
If the first condition is TRUE, PHP checks whether the person has a driving license.
Since both conditions are TRUE, the message
You are eligible to drive.is displayed.
6. PHP Switch Statement
The switch statement is used to execute one block of code from multiple possible options.
It is useful when we want to compare one expression against multiple possible values.
Syntax:
switch (expression) {
case value1:
// Code to execute
break;
case value2:
// Code to execute
break;
default:
// Code if no case matches
}Example:
<?php
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
default:
echo "Invalid Day";
}
?>Output:
WednesdayHere:
$daycontains the value 3.PHP checks each case.
When it finds
case 3, it executes the corresponding code.The
breakstatement stops the switch execution.The
defaultblock executes only when no case matches.
7. What is the Break Statement in PHP?
The break statement is used to terminate the execution of a switch statement or loop.
In a switch statement, break prevents PHP from executing the remaining cases after a matching case.
Example:
<?php
$number = 2;
switch ($number) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
default:
echo "Invalid Number";
}
?>Output:
Two8. What is the Default Statement in PHP Switch?
The default statement is used to execute code when none of the specified cases match the switch expression.
Example:
<?php
$day = 10;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
default:
echo "Invalid Day";
}
?>Output:
Invalid Day9. PHP Match Expression
PHP introduced the match expression in PHP 8.0.
It is similar to the switch statement, but it uses strict comparison (===) and returns a value.
Unlike switch, the match expression does not require a break statement.
Example:
<?php
$day = 3;
$result = match ($day) {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
default => "Invalid Day"
};
echo $result;
?>Output:
WednesdayHere, the match expression compares the value of $day with the given options and returns the matching result.
10. Difference Between If-Else and Switch Statements
If-Else | Switch |
|---|---|
Used to check conditions. | Used to compare an expression against multiple values. |
Supports complex conditions. | Best suited for matching specific values. |
Uses | Uses |
Does not require | Usually uses |
Can compare ranges and multiple expressions. | Traditionally compares one expression against case values. |
11. Real-Life Example of Conditional Statements
Let's create a simple PHP program to check whether a student has passed or failed based on marks.
Example:
<?php
$studentName = "Rehan";
$marks = 85;
echo "Student Name: " . $studentName;
echo "<br>";
echo "Total Marks: " . $marks;
echo "<br>";
if ($marks >= 90) {
echo "Result: Excellent";
} elseif ($marks >= 75) {
echo "Result: Very Good";
} elseif ($marks >= 60) {
echo "Result: Good";
} elseif ($marks >= 40) {
echo "Result: Pass";
} else {
echo "Result: Fail";
}
?>Output:
Student Name: Rehan
Total Marks: 85
Result: Very Good12. Advantages of Conditional Statements in PHP
Conditional statements help programs make decisions.
They allow developers to execute code based on specific conditions.
They make programs dynamic and flexible.
They help validate user input.
They are useful for login and registration systems.
They help implement business logic in web applications.
They make it easier to handle multiple conditions.
13. Conclusion
Conditional statements are an important part of PHP programming. They allow developers to control program execution based on different conditions.
PHP provides if, if-else, elseif, nested if, switch, and match to implement decision-making logic.
Understanding conditional statements is essential for developing dynamic websites, authentication systems, student management systems, and other web applications.
PHP Functions – How to Create, Declare, and Call Functions in PHP with Examples
PHP functions are reusable blocks of code that perform a specific task. Instead of writing the same code repeatedly, you can create a function once and call it whenever needed.
In this tutorial, you will learn how to create and use PHP functions, pass parameters, return values, and work with different types of arguments.
1. What is a Function in PHP?
A function is a block of code designed to perform a particular task. It executes only when it is called.
Example:
<?php
function sayHello() {
echo "Hello, Welcome to LearnWithRehan!";
}
sayHello();
?>Output:
Hello, Welcome to LearnWithRehan!In this example:
functionis the keyword used to declare a function.sayHello()is the function name.echodisplays the message.sayHello()calls the function.
2. PHP Function Syntax
The basic syntax of a PHP function is:
function functionName() {
// Code to execute
}To execute the function, call it using its name:
functionName();3. Creating a Function with Parameters
Parameters allow you to pass information to a function.
Example:
<?php
function greet($name) {
echo "Hello, " . $name;
}
greet("Rehan");
?>Output:
Hello, RehanHere, $name is a parameter that receives the value "Rehan".
4. PHP Function with Multiple Parameters
A function can accept multiple parameters.
Example:
<?php
function addNumbers($a, $b) {
echo "Sum = " . ($a + $b);
}
addNumbers(10, 20);
?>Output:
Sum = 30In this example:
$areceives10.$breceives20.The function adds both values and displays the result.
5. PHP Function with Return Value
The return statement sends a value back from a function. You can store that returned value in a variable.
Example:
<?php
function multiply($a, $b) {
return $a * $b;
}
$result = multiply(5, 4);
echo "Multiplication = " . $result;
?>Output:
Multiplication = 20Important: return sends the result back to the calling code. It does not automatically display the result.
6. PHP Function with Default Parameters
You can assign a default value to a parameter. If no argument is provided, PHP uses that default value.
Example:
<?php
function welcome($name = "Guest") {
echo "Welcome, " . $name;
}
welcome();
echo "<br>";
welcome("Rehan");
?>Output:
Welcome, Guest
Welcome, RehanIn this example:
When no value is passed,
"Guest"is used.When
"Rehan"is passed, it replaces the default value.
7. PHP Function with Type Declaration
PHP allows you to specify the expected data type of function parameters and return values.
Example:
<?php
function add(int $a, int $b): int {
return $a + $b;
}
$result = add(10, 20);
echo $result;
?>Output:
30Here:
int $ameans the first parameter is expected to be an integer.int $bmeans the second parameter is expected to be an integer.: intspecifies that the function returns an integer.
8. PHP Function with Variable Number of Arguments
Sometimes you may not know how many arguments will be passed to a function. PHP supports variable-length arguments using ....
Example:
<?php
function sumNumbers(...$numbers) {
$sum = 0;
foreach ($numbers as $number) {
$sum += $number;
}
return $sum;
}
echo sumNumbers(10, 20, 30);
?>Output:
60The ...$numbers syntax collects all supplied arguments into an array.
9. PHP Anonymous Functions
An anonymous function is a function without a name. It can be assigned to a variable and called using that variable.
Example:
<?php
$greet = function($name) {
return "Hello, " . $name;
};
echo $greet("Rehan");
?>Output:
Hello, RehanAnonymous functions are also called closures in PHP when used with closure features.
10. PHP Arrow Functions
Arrow functions provide a shorter way to write simple functions. They were introduced in PHP 7.4.
Syntax:
fn(parameters) => expression;Example:
<?php
$add = fn($a, $b) => $a + $b;
echo $add(10, 20);
?>Output:
30Arrow functions automatically capture variables from the parent scope by value.
11. PHP Recursive Functions
A recursive function is a function that calls itself. It is useful for solving problems that can be divided into smaller versions of the same problem.
Example: Factorial using recursion
<?php
function factorial($number) {
if ($number <= 1) {
return 1;
}
return $number * factorial($number - 1);
}
echo factorial(5);
?>Output:
120Explanation:
factorial(5)calculates5 × 4 × 3 × 2 × 1.When the number becomes
1, the function returns1.The final result is
120.
12. PHP Built-in Functions
PHP provides many predefined functions that you can use directly without creating them yourself.
Some commonly used built-in functions are:
Function | Description | Example |
|---|---|---|
| Returns string length |
|
| Converts text to uppercase |
|
| Converts text to lowercase |
|
| Counts array elements |
|
| Returns formatted date |
|
| Rounds a number |
|
| Returns the largest value |
|
| Returns the smallest value |
|
Example:
<?php
$name = "LearnWithRehan";
echo strlen($name);
echo "<br>";
echo strtoupper($name);
echo "<br>";
echo strtolower($name);
?>Output:
14
LEARNWITHREHAN
learnwithrehan13. Difference Between Parameters and Arguments
These two terms are related but have different meanings.
Parameters | Arguments |
|---|---|
Variables defined in the function declaration. | Actual values passed when calling the function. |
Receive the supplied values. | Provide values to the function. |
Example: | Example: |
Example:
<?php
function add($a, $b) {
return $a + $b;
}
echo add(10, 20);
?>Here, $a and $b are parameters, while 10 and 20 are arguments.
14. Advantages of PHP Functions
Code Reusability: Write code once and use it multiple times.
Less Code: Avoid writing the same code repeatedly.
Easy Maintenance: Update code in one place.
Better Organization: Divide a large program into smaller sections.
Easy Debugging: Find and fix errors more easily.
Improved Readability: Make programs easier to understand.
15. Complete Practical Example – PHP Calculator Using Functions
Let's create a simple calculator using PHP functions.
<?php
function add($a, $b) {
return $a + $b;
}
function subtract($a, $b) {
return $a - $b;
}
function multiply($a, $b) {
return $a * $b;
}
function divide($a, $b) {
if ($b == 0) {
return "Cannot divide by zero";
}
return $a / $b;
}
$num1 = 20;
$num2 = 10;
echo "Addition: " . add($num1, $num2);
echo "<br>";
echo "Subtraction: " . subtract($num1, $num2);
echo "<br>";
echo "Multiplication: " . multiply($num1, $num2);
echo "<br>";
echo "Division: " . divide($num1, $num2);
?>Output:
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2This example demonstrates how multiple functions can be used to organize a single PHP application.
Conclusion
PHP functions help developers write reusable, organized, and maintainable code. You can create your own functions, pass parameters, return values, use default arguments, and also use PHP's built-in functions.
Understanding functions is an important step toward developing dynamic PHP websites and applications.
PHP Arrays – Indexed, Associative, and Multidimensional Arrays with Examples
Arrays are an important concept in PHP. They allow you to store multiple values in a single variable instead of creating separate variables for each value.
For example, if you want to store the names of five students, you can use an array instead of creating five different variables.
In this tutorial, you will learn about PHP arrays, their types, how to access and modify array elements, and commonly used array functions.
1. What is an Array in PHP?
An array is a variable that can store multiple values under a single name.
Example:
<?php
$students = array("Rehan", "Amit", "Rahul", "Priya");
echo $students[0];
?>Output:
RehanHere:
$studentsis an array variable."Rehan","Amit","Rahul", and"Priya"are array elements.$students[0]accesses the first element.
Important: PHP array indexing starts from 0 for automatically indexed arrays.
2. Types of Arrays in PHP
PHP mainly supports three types of arrays:
Indexed Array
Associative Array
Multidimensional Array
Let's understand each type with examples.
3. Indexed Array in PHP
An indexed array is an array in which elements are stored with numeric indexes.
You can create an indexed array using the array() function or the short array syntax [].
Example 1: Using array()
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0];
?>Output:
RedExample 2: Using Short Array Syntax
<?php
$colors = ["Red", "Green", "Blue"];
echo $colors[1];
?>Output:
GreenAccessing All Elements Using a Loop
You can use a foreach loop to display all array elements.
<?php
$colors = ["Red", "Green", "Blue", "Yellow"];
foreach ($colors as $color) {
echo $color . "<br>";
}
?>Output:
Red
Green
Blue
YellowAdding Elements to an Indexed Array
You can add a new element using the [] operator.
<?php
$fruits = ["Apple", "Banana", "Mango"];
$fruits[] = "Orange";
print_r($fruits);
?>Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
)Updating Array Elements
You can update an element by accessing its index.
<?php
$fruits = ["Apple", "Banana", "Mango"];
$fruits[1] = "Orange";
print_r($fruits);
?>Output:
Array
(
[0] => Apple
[1] => Orange
[2] => Mango
)4. Associative Array in PHP
An associative array stores values using named keys instead of numeric indexes.
It is useful when you want to store information with meaningful names.
Example:
<?php
$student = [
"name" => "Rehan",
"age" => 25,
"city" => "Delhi"
];
echo $student["name"];
?>Output:
RehanHere:
name,age, andcityare keys.Rehan,25, andDelhiare values.
Displaying All Associative Array Elements
You can use a foreach loop with two variables to access both keys and values.
<?php
$student = [
"name" => "Rehan",
"age" => 25,
"city" => "Delhi"
];
foreach ($student as $key => $value) {
echo $key . " : " . $value . "<br>";
}
?>Output:
name : Rehan
age : 25
city : DelhiAdding and Updating Associative Array Elements
<?php
$student = [
"name" => "Rehan",
"age" => 25
];
// Add new element
$student["city"] = "Delhi";
// Update existing element
$student["age"] = 26;
print_r($student);
?>Output:
Array
(
[name] => Rehan
[age] => 26
[city] => Delhi
)5. Multidimensional Array in PHP
A multidimensional array is an array that contains one or more arrays inside it.
It is useful when you need to store data in rows and columns, such as student records, employee details, or product information.
Example:
<?php
$students = [
["Rehan", 25, "Delhi"],
["Amit", 22, "Mumbai"],
["Rahul", 24, "Jaipur"]
];
echo $students[0][0];
?>Output:
RehanIn this example:
$students[0]accesses the first student's record.$students[0][0]accesses the first student's name.$students[1][1]accesses the second student's age.
Displaying a Multidimensional Array Using Nested Loops
<?php
$students = [
["Rehan", 25, "Delhi"],
["Amit", 22, "Mumbai"],
["Rahul", 24, "Jaipur"]
];
for ($i = 0; $i < count($students); $i++) {
for ($j = 0; $j < count($students[$i]); $j++) {
echo $students[$i][$j] . " ";
}
echo "<br>";
}
?>Output:
Rehan 25 Delhi
Amit 22 Mumbai
Rahul 24 JaipurMultidimensional Associative Array
You can also create multidimensional arrays using associative keys.
<?php
$students = [
"student1" => [
"name" => "Rehan",
"age" => 25,
"city" => "Delhi"
],
"student2" => [
"name" => "Amit",
"age" => 22,
"city" => "Mumbai"
]
];
echo $students["student1"]["name"];
?>Output:
Rehan6. Counting Array Elements Using count()
The count() function returns the total number of elements in an array.
Example:
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
echo count($fruits);
?>Output:
47. Adding Elements Using array_push()
The array_push() function adds one or more elements to the end of an array.
Example:
<?php
$fruits = ["Apple", "Banana"];
array_push($fruits, "Mango", "Orange");
print_r($fruits);
?>Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
)8. Removing Elements Using array_pop()
The array_pop() function removes the last element from an array.
Example:
<?php
$fruits = ["Apple", "Banana", "Mango"];
array_pop($fruits);
print_r($fruits);
?>Output:
Array
(
[0] => Apple
[1] => Banana
)9. Removing Elements Using array_shift()
The array_shift() function removes the first element from an array.
Example:
<?php
$fruits = ["Apple", "Banana", "Mango"];
array_shift($fruits);
print_r($fruits);
?>Output:
Array
(
[0] => Banana
[1] => Mango
)10. Searching Elements Using in_array()
The in_array() function checks whether a value exists in an array.
It returns true if the value is found and false otherwise.
Example:
<?php
$fruits = ["Apple", "Banana", "Mango"];
if (in_array("Banana", $fruits)) {
echo "Fruit Found";
} else {
echo "Fruit Not Found";
}
?>Output:
Fruit FoundYou can also use strict checking:
in_array(10, $numbers, true);The third argument true checks both the value and its data type.
11. Sorting Arrays in PHP
PHP provides different functions to sort arrays.
Function | Description |
|---|---|
| Sorts values in ascending order |
| Sorts values in descending order |
| Sorts associative array by value, maintaining key association |
| Sorts associative array by value in descending order |
| Sorts associative array by key in ascending order |
| Sorts associative array by key in descending order |
Example: sort()
<?php
$numbers = [40, 10, 30, 20];
sort($numbers);
print_r($numbers);
?>Output:
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
)Example: rsort()
<?php
$numbers = [40, 10, 30, 20];
rsort($numbers);
print_r($numbers);
?>Output:
Array
(
[0] => 40
[1] => 30
[2] => 20
[3] => 10
)Example: ksort()
<?php
$student = [
"city" => "Delhi",
"name" => "Rehan",
"age" => 25
];
ksort($student);
print_r($student);
?>Output:
Array
(
[age] => 25
[city] => Delhi
[name] => Rehan
)12. Merging Arrays Using array_merge()
The array_merge() function combines two or more arrays into one array.
Example:
<?php
$array1 = ["Apple", "Banana"];
$array2 = ["Mango", "Orange"];
$result = array_merge($array1, $array2);
print_r($result);
?>Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
)13. Converting an Array into a String Using implode()
The implode() function joins array elements into a single string using a specified separator.
Example:
<?php
$fruits = ["Apple", "Banana", "Mango"];
$result = implode(", ", $fruits);
echo $result;
?>Output:
Apple, Banana, Mango14. Converting a String into an Array Using explode()
The explode() function splits a string into an array based on a separator.
Example:
<?php
$names = "Rehan,Amit,Rahul";
$result = explode(",", $names);
print_r($result);
?>Output:
Array
(
[0] => Rehan
[1] => Amit
[2] => Rahul
)15. Checking Array Keys and Values
PHP provides functions to check whether a particular key or value exists in an array.
array_key_exists()checks whether a key exists.isset()checks whether a key exists and its value is notNULL.
Example:
<?php
$student = [
"name" => "Rehan",
"age" => 25,
"city" => "Delhi"
];
if (array_key_exists("name", $student)) {
echo "Name key exists";
}
echo "<br>";
if (isset($student["age"])) {
echo "Age value is set";
}
?>Output:
Name key exists
Age value is set16. Difference Between Indexed, Associative, and Multidimensional Arrays
Indexed Array | Associative Array | Multidimensional Array |
|---|---|---|
Uses numeric indexes. | Uses named or other keys. | Contains arrays inside arrays. |
Access values using numeric indexes. | Access values using keys. | Access values using multiple indexes or keys. |
Example: | Example: | Example: |
17. Complete Practical Example – Student Records Using PHP Arrays
Let's create a practical example that stores multiple student records and displays them in an HTML table.
<?php
$students = [
[
"name" => "Rehan",
"age" => 25,
"city" => "Delhi"
],
[
"name" => "Amit",
"age" => 22,
"city" => "Mumbai"
],
[
"name" => "Rahul",
"age" => 24,
"city" => "Jaipur"
]
];
?>
<!DOCTYPE html>
<html>
<head>
<title>Student Records</title>
</head>
<body>
<h2>Student Records</h2>
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<?php foreach ($students as $student) { ?>
<tr>
<td><?php echo htmlspecialchars($student["name"]); ?></td>
<td><?php echo htmlspecialchars((string)$student["age"]); ?></td>
<td><?php echo htmlspecialchars($student["city"]); ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>Output:
Student Records
Name | Age | City |
|---|---|---|
Rehan | 25 | Delhi |
Amit | 22 | Mumbai |
Rahul | 24 | Jaipur |
This example demonstrates how PHP arrays can store multiple records and display them dynamically in an HTML table.
18. Advantages of Arrays in PHP
Store Multiple Values: Store many values in a single variable.
Easy Data Management: Organize related information together.
Code Reusability: Use loops to process multiple elements.
Easy Searching: Find values using built-in functions.
Sorting: Arrange data in ascending or descending order.
Database Applications: Store and display records retrieved from databases.
Conclusion
PHP arrays are useful for storing and managing multiple values. PHP supports indexed, associative, and multidimensional arrays. With built-in functions like count(), array_push(), array_merge(), sort(), explode(), and implode(), you can easily manage and manipulate array data.
Understanding arrays is essential for developing dynamic websites, handling form data, and working with databases in PHP.
PHP Strings – String Functions, Concatenation, Searching, Replacing and Formatting with Examples
Strings are one of the most commonly used data types in PHP. A string is a sequence of characters enclosed in single quotes or double quotes.
PHP provides many built-in string functions that help developers manipulate, search, replace, format, and work with text.
In this tutorial, you will learn PHP strings from beginner to advanced level with practical examples.
1. What is a String in PHP?
A string is a collection of characters such as letters, numbers, symbols, and spaces.
Example:
<?php
$name = "LearnWithRehan";
$message = 'Welcome to PHP Course';
echo $name;
echo "<br>";
echo $message;
?>Output:
LearnWithRehan
Welcome to PHP CoursePHP supports two main ways to declare strings:
Single quotes (
' ')Double quotes (
" ")
2. Single Quotes vs Double Quotes in PHP
Both single and double quotes are used to create strings, but they behave differently.
Example:
<?php
$name = "Rehan";
echo 'Hello $name';
echo "<br>";
echo "Hello $name";
?>Output:
Hello $name
Hello RehanDifference:
Single Quotes | Double Quotes |
|---|---|
Variables are not interpreted. | Variables are interpreted. |
Most escape sequences are treated literally. | Supports escape sequences such as |
Useful for simple text. | Useful for text containing variables. |
3. String Concatenation in PHP
String concatenation means joining two or more strings together.
PHP uses the dot (.) operator to concatenate strings.
Example:
<?php
$firstName = "Rehan";
$lastName = "Khan";
$fullName = $firstName . " " . $lastName;
echo $fullName;
?>Output:
Rehan KhanUsing the Concatenation Assignment Operator (.=)
The .= operator appends text to an existing string.
<?php
$message = "Welcome";
$message .= " to LearnWithRehan";
echo $message;
?>Output:
Welcome to LearnWithRehan4. String Length Using strlen()
The strlen() function returns the number of bytes in a string.
Example:
<?php
$name = "LearnWithRehan";
echo strlen($name);
?>Output:
14Note: strlen() counts bytes, not necessarily visible characters. For UTF-8 text containing characters such as Hindi letters, use mb_strlen() to count characters correctly.
5. Convert String to Uppercase Using strtoupper()
The strtoupper() function converts English lowercase letters into uppercase letters.
Example:
<?php
$text = "learn with rehan";
echo strtoupper($text);
?>Output:
LEARN WITH REHAN6. Convert String to Lowercase Using strtolower()
The strtolower() function converts English uppercase letters into lowercase letters.
Example:
<?php
$text = "LEARN WITH REHAN";
echo strtolower($text);
?>Output:
learn with rehan7. Convert First Character to Uppercase Using ucfirst()
The ucfirst() function converts the first character of a string to uppercase.
Example:
<?php
$text = "learn with rehan";
echo ucfirst($text);
?>Output:
Learn with rehan8. Convert Each Word to Uppercase Using ucwords()
The ucwords() function converts the first character of each word to uppercase.
Example:
<?php
$text = "welcome to learn with rehan";
echo ucwords($text);
?>Output:
Welcome To Learn With Rehan9. Remove Spaces Using trim(), ltrim() and rtrim()
PHP provides three useful functions to remove whitespace from strings.
trim()removes whitespace from both ends.ltrim()removes whitespace from the beginning.rtrim()removes whitespace from the end.
Example:
<?php
$text = " LearnWithRehan ";
echo trim($text);
echo "<br>";
echo ltrim($text);
echo "<br>";
echo rtrim($text);
?>Output:
LearnWithRehan
LearnWithRehan
LearnWithRehanThese functions are especially useful when processing form input.
10. Find Text Position Using strpos()
The strpos() function finds the position of the first occurrence of a substring inside a string.
Example:
<?php
$text = "Welcome to LearnWithRehan";
$position = strpos($text, "Learn");
if ($position !== false) {
echo "Text found at position: " . $position;
} else {
echo "Text not found";
}
?>Output:
Text found at position: 11Important: String positions start from 0. Always use !== false because a match at position 0 is valid.
11. Search Text Without Case Sensitivity Using stripos()
The stripos() function searches for text without distinguishing between uppercase and lowercase English letters.
Example:
<?php
$text = "Welcome to LearnWithRehan";
$position = stripos($text, "learn");
if ($position !== false) {
echo "Text found at position: " . $position;
} else {
echo "Text not found";
}
?>Output:
Text found at position: 1112. Replace Text Using str_replace()
The str_replace() function replaces a specific word or text with another value.
Syntax:
str_replace(search, replace, subject);Example:
<?php
$text = "Welcome to PHP";
$result = str_replace("PHP", "LearnWithRehan", $text);
echo $result;
?>Output:
Welcome to LearnWithRehan13. Replace Text Without Case Sensitivity Using str_ireplace()
The str_ireplace() function replaces text without case-sensitive matching.
Example:
<?php
$text = "Welcome to php";
$result = str_ireplace("PHP", "LearnWithRehan", $text);
echo $result;
?>Output:
Welcome to LearnWithRehan14. Extract Part of a String Using substr()
The substr() function extracts a portion of a string.
Syntax:
substr(string, start, length);Example:
<?php
$text = "LearnWithRehan";
echo substr($text, 0, 5);
echo "<br>";
echo substr($text, 5, 4);
?>Output:
Learn
WithHere:
0is the starting position.5is the number of characters to extract in the first example.
15. Compare Strings Using strcmp()
The strcmp() function compares two strings in a case-sensitive manner.
It returns:
0if both strings are equal.A negative value if the first string is smaller.
A positive value if the first string is greater.
Example:
<?php
$str1 = "Hello";
$str2 = "Hello";
if (strcmp($str1, $str2) == 0) {
echo "Both strings are equal";
} else {
echo "Strings are not equal";
}
?>Output:
Both strings are equal16. Repeat a String Using str_repeat()
The str_repeat() function repeats a string a specified number of times.
Example:
<?php
echo str_repeat("PHP ", 3);
?>Output:
PHP PHP PHP17. Reverse a String Using strrev()
The strrev() function reverses a string.
Example:
<?php
$text = "HELLO";
echo strrev($text);
?>Output:
OLLEH18. Count Words Using str_word_count()
The str_word_count() function counts the number of words in a string.
Example:
<?php
$text = "Welcome to LearnWithRehan PHP Course";
echo str_word_count($text);
?>Output:
519. Split a String Using explode()
The explode() function converts a string into an array based on a specified separator.
Example:
<?php
$text = "Apple,Banana,Mango,Orange";
$fruits = explode(",", $text);
print_r($fruits);
?>Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
)20. Join Array Elements Using implode()
The implode() function joins array elements into a single string.
Example:
<?php
$fruits = ["Apple", "Banana", "Mango"];
$result = implode(" - ", $fruits);
echo $result;
?>Output:
Apple - Banana - Mango21. Check Whether a String Contains Text Using str_contains()
The str_contains() function checks whether a string contains a particular substring.
It was introduced in PHP 8.0.
Example:
<?php
$text = "Welcome to LearnWithRehan";
if (str_contains($text, "Rehan")) {
echo "Text exists";
} else {
echo "Text does not exist";
}
?>Output:
Text exists22. Check Whether a String Starts or Ends With Specific Text
PHP provides two useful functions:
str_starts_with()checks whether a string starts with specific text.str_ends_with()checks whether a string ends with specific text.
Both functions were introduced in PHP 8.0.
Example:
<?php
$text = "LearnWithRehan";
if (str_starts_with($text, "Learn")) {
echo "String starts with Learn";
}
echo "<br>";
if (str_ends_with($text, "Rehan")) {
echo "String ends with Rehan";
}
?>Output:
String starts with Learn
String ends with Rehan23. String Formatting Using sprintf()
The sprintf() function formats a string according to specified placeholders and returns the formatted string.
Example:
<?php
$name = "Rehan";
$age = 25;
$message = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $message;
?>Output:
My name is Rehan and I am 25 years old.Common format specifiers:
Specifier | Description |
|---|---|
| String |
| Integer |
| Floating-point number |
| Floating-point number with 2 decimal places |
24. Convert Special Characters Using htmlspecialchars()
The htmlspecialchars() function converts special HTML characters into HTML entities.
It is useful when displaying user-provided text on a webpage to help prevent HTML injection and cross-site scripting (XSS).
Example:
<?php
$text = "<h1>Hello PHP</h1>";
echo htmlspecialchars($text, ENT_QUOTES, "UTF-8");
?>Output displayed in the browser:
<h1>Hello PHP</h1>The browser displays the HTML tags as text instead of interpreting them as HTML elements.
25. Difference Between Common PHP String Functions
Function | Description |
|---|---|
| Returns the string length in bytes |
| Converts text to uppercase |
| Converts text to lowercase |
| Capitalizes the first character |
| Capitalizes the first character of each word |
| Removes whitespace from both ends |
| Finds the position of text |
| Replaces text |
| Extracts part of a string |
| Compares two strings |
| Reverses a string |
| Converts a string into an array |
| Converts an array into a string |
| Checks whether text exists |
26. Complete Practical Example – PHP Student Information
Let's create a practical example using different PHP string functions.
<?php
$name = " rehan khan ";
$email = "REHAN@GMAIL.COM";
$course = "PHP Programming Course";
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP String Example</title>
</head>
<body>
<h2>Student Information</h2>
<?php
$cleanName = trim($name);
echo "Name: " . ucwords($cleanName);
echo "<br>";
echo "Email: " . strtolower($email);
echo "<br>";
echo "Course: " . strtoupper($course);
echo "<br>";
echo "Name Length: " . strlen($cleanName);
echo "<br>";
echo "Course Name: " . str_replace("PHP", "Advanced PHP", $course);
?>
</body>
</html>Output:
Student Information
Name: Rehan Khan
Email: rehan@gmail.com
Course: PHP PROGRAMMING COURSE
Name Length: 10
Course Name: Advanced PHP Programming Course
27. Advantages of PHP String Functions
Easy Text Manipulation: Easily modify and format text.
Searching: Find specific words or characters inside strings.
Replacing: Replace existing text with new content.
Data Validation: Process and clean user input.
Formatting: Display text in a structured format.
Security: Escape special HTML characters before displaying user input.
Database Applications: Process names, addresses, emails, and other text data.
Conclusion
PHP strings are essential for handling text in dynamic websites and applications. PHP provides many built-in functions such as strlen(), strtoupper(), str_replace(), strpos(), substr(), explode(), and implode() to make string manipulation easy.
Understanding PHP string functions will help you work with user input, form data, database records, and dynamic web content.
PHP Numbers – Integers, Floats, Mathematical Operations and Number Functions with Examples
Numbers are an important part of PHP programming. They are used to perform calculations, manage prices, calculate percentages, process quantities, and work with mathematical operations.
PHP mainly supports two numeric data types:
Integer
Float (Floating-Point Number)
PHP also provides several built-in functions to perform mathematical calculations, round numbers, generate random numbers, and check numeric values.
In this tutorial, you will learn how to work with numbers in PHP with practical examples.
1. What are Numbers in PHP?
Numbers are values used to perform mathematical calculations and numeric operations.
PHP supports different types of numeric values, such as integers and floating-point numbers.
Example:
<?php
$age = 25;
$price = 199.99;
echo $age;
echo "<br>";
echo $price;
?>Output:
25
199.992. Integer in PHP
An integer is a whole number without a decimal point.
Examples of integers:
10
100
-25
0
5000
Example:
<?php
$a = 100;
$b = -50;
$c = 0;
echo $a;
echo "<br>";
echo $b;
echo "<br>";
echo $c;
?>Output:
100
-50
03. Float in PHP
A float is a number that contains a decimal point or represents a fractional value.
Examples:
10.5
99.99
3.14
-25.75
Example:
<?php
$price = 199.99;
$percentage = 85.5;
$temperature = -10.5;
echo $price;
echo "<br>";
echo $percentage;
echo "<br>";
echo $temperature;
?>Output:
199.99
85.5
-10.54. Difference Between Integer and Float
Integer | Float |
|---|---|
Stores whole numbers. | Stores numbers with fractional parts. |
Does not contain a decimal point. | Usually contains a decimal point. |
Example: | Example: |
Used for counts and quantities. | Used for prices, measurements, and percentages. |
5. Check Whether a Variable is Numeric Using is_numeric()
The is_numeric() function checks whether a value is a number or a numeric string.
It returns true if the value is numeric; otherwise, it returns false.
Example:
<?php
$a = 100;
$b = "250";
$c = "Hello";
var_dump(is_numeric($a));
echo "<br>";
var_dump(is_numeric($b));
echo "<br>";
var_dump(is_numeric($c));
?>Output:
bool(true)
bool(true)
bool(false)6. Check Integer Using is_int()
The is_int() function checks whether a variable contains an integer.
Example:
<?php
$a = 100;
$b = 10.5;
$c = "100";
var_dump(is_int($a));
echo "<br>";
var_dump(is_int($b));
echo "<br>";
var_dump(is_int($c));
?>Output:
bool(true)
bool(false)
bool(false)Important: A numeric string such as "100" is not an integer variable.
7. Check Float Using is_float()
The is_float() function checks whether a variable contains a floating-point number.
Example:
<?php
$a = 10.5;
$b = 100;
var_dump(is_float($a));
echo "<br>";
var_dump(is_float($b));
?>Output:
bool(true)
bool(false)8. Mathematical Operations in PHP
PHP supports different mathematical operations using arithmetic operators.
Operator | Operation | Example |
|---|---|---|
| Addition |
|
| Subtraction |
|
| Multiplication |
|
| Division |
|
| Modulus (remainder) |
|
| Exponentiation |
|
Example:
<?php
$a = 20;
$b = 10;
echo "Addition: " . ($a + $b);
echo "<br>";
echo "Subtraction: " . ($a - $b);
echo "<br>";
echo "Multiplication: " . ($a * $b);
echo "<br>";
echo "Division: " . ($a / $b);
echo "<br>";
echo "Modulus: " . ($a % 3);
echo "<br>";
echo "Power: " . ($a ** 2);
?>Output:
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Modulus: 2
Power: 4009. Absolute Value Using abs()
The abs() function returns the absolute value of a number. It removes the negative sign.
Example:
<?php
$num = -150;
echo abs($num);
?>Output:
15010. Round Numbers Using round()
The round() function rounds a floating-point number to the nearest integer by default.
You can also specify the number of decimal places.
Example:
<?php
echo round(10.4);
echo "<br>";
echo round(10.6);
echo "<br>";
echo round(10.567, 2);
?>Output:
10
11
10.5711. Round Down Using floor()
The floor() function rounds a number down to the nearest integer.
Example:
<?php
echo floor(10.9);
echo "<br>";
echo floor(15.2);
?>Output:
10
1512. Round Up Using ceil()
The ceil() function rounds a number up to the nearest integer.
Example:
<?php
echo ceil(10.2);
echo "<br>";
echo ceil(15.8);
?>Output:
11
1613. Find the Largest Number Using max()
The max() function returns the largest value from the given values or array.
Example:
<?php
echo max(10, 20, 50, 30, 40);
?>Output:
50Using an Array:
<?php
$numbers = [10, 50, 20, 80, 30];
echo max($numbers);
?>Output:
8014. Find the Smallest Number Using min()
The min() function returns the smallest value from the given values or array.
Example:
<?php
echo min(10, 20, 5, 30, 40);
?>Output:
515. Calculate Power Using pow()
The pow() function calculates the power of a number.
Syntax:
pow(base, exponent);Example:
<?php
echo pow(2, 3);
echo "<br>";
echo pow(5, 2);
?>Output:
8
25Explanation:
2³ = 2 × 2 × 2 = 85² = 5 × 5 = 25
16. Find Square Root Using sqrt()
The sqrt() function returns the square root of a number.
Example:
<?php
echo sqrt(25);
echo "<br>";
echo sqrt(100);
?>Output:
5
1017. Generate Random Numbers Using rand()
The rand() function generates a random integer.
You can provide a minimum and maximum value.
Example:
<?php
echo rand(1, 100);
?>Possible Output:
57The output may be different each time you run the program.
Important: rand() is not suitable for generating security-sensitive random values. Use random_int() for that purpose.
18. Generate Secure Random Numbers Using random_int()
The random_int() function generates a cryptographically secure random integer within a specified range.
Example:
<?php
echo random_int(1000, 9999);
?>Possible Output:
4827The generated number may be different each time.
19. Number Formatting Using number_format()
The number_format() function formats a number with grouped thousands and optional decimal places.
Syntax:
number_format(number, decimals, decimal_separator, thousands_separator);Example:
<?php
$price = 1234567.895;
echo number_format($price, 2);
?>Output:
1,234,567.90Example with Indian Number Formatting
<?php
$amount = 1234567.89;
echo number_format($amount, 2, ".", ",");
?>Output:
1,234,567.89For Indian-style grouping such as 12,34,567.89, you can use the NumberFormatter class from PHP's Intl extension:
<?php
$formatter = new NumberFormatter("en_IN", NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $formatter->format(1234567.89);
?>Output:
12,34,567.8920. Find the Remainder Using fmod()
The fmod() function returns the floating-point remainder after division.
Example:
<?php
echo fmod(10.5, 3);
?>Output:
1.521. Check Whether a Number is Finite Using is_finite()
The is_finite() function checks whether a number is a finite floating-point value.
Example:
<?php
$num = 100.50;
var_dump(is_finite($num));
?>Output:
bool(true)22. Check Whether a Number is Infinite Using is_infinite()
The is_infinite() function checks whether a floating-point value is infinite.
Example:
<?php
$num = INF;
var_dump(is_infinite($num));
?>Output:
bool(true)23. Check Whether a Number is Not a Number Using is_nan()
The is_nan() function checks whether a floating-point value is NaN (Not a Number).
Example:
<?php
$num = acos(8);
var_dump(is_nan($num));
?>Output:
bool(true)24. Type Conversion in PHP Numbers
PHP allows you to convert one data type into another.
You can convert a numeric string or float into an integer or convert an integer into a float.
Example:
<?php
$num1 = "100";
$num2 = 25.75;
$num3 = 50;
$intValue = (int)$num1;
$floatValue = (float)$num3;
$convertedInt = (int)$num2;
echo $intValue;
echo "<br>";
echo $floatValue;
echo "<br>";
echo $convertedInt;
?>Output:
100
50
25Important: Converting a float to an integer using (int) removes the fractional part; it does not round the number.
25. Difference Between Common PHP Number Functions
Function | Description |
|---|---|
| Checks whether a value is numeric |
| Checks whether a value is an integer |
| Checks whether a value is a float |
| Returns absolute value |
| Rounds a number |
| Rounds down |
| Rounds up |
| Returns the largest value |
| Returns the smallest value |
| Calculates power |
| Calculates square root |
| Generates a random integer |
| Generates a secure random integer |
| Formats a number |
| Returns floating-point remainder |
26. Complete Practical Example – PHP Student Marks Calculator
Let's create a practical example that calculates total marks, percentage, and grade using PHP.
<?php
$studentName = "Rehan";
$subject1 = 85;
$subject2 = 90;
$subject3 = 78;
$subject4 = 88;
$subject5 = 95;
$total = $subject1 + $subject2 + $subject3 + $subject4 + $subject5;
$percentage = ($total / 500) * 100;
if ($percentage >= 90) {
$grade = "A+";
} elseif ($percentage >= 80) {
$grade = "A";
} elseif ($percentage >= 70) {
$grade = "B";
} elseif ($percentage >= 60) {
$grade = "C";
} else {
$grade = "Fail";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Student Marks Calculator</title>
</head>
<body>
<h2>Student Result</h2>
<?php
echo "Student Name: " . $studentName;
echo "<br>";
echo "Total Marks: " . $total;
echo "<br>";
echo "Percentage: " . number_format($percentage, 2) . "%";
echo "<br>";
echo "Grade: " . $grade;
?>
</body>
</html>Output:
Student Result
Student Name: Rehan
Total Marks: 436
Percentage: 87.20%
Grade: A
This example demonstrates how PHP numeric operations and conditional statements can be used together to create a practical marks calculator.
27. Advantages of PHP Number Functions
Easy Calculations: Perform addition, subtraction, multiplication, and division.
Number Formatting: Display numbers in a readable format.
Rounding: Round decimal values as required.
Random Number Generation: Generate random or secure random numbers.
Type Checking: Check whether a value is an integer, float, or numeric string.
Mathematical Operations: Calculate square roots, powers, and remainders.
Practical Applications: Build calculators, billing systems, result systems, and financial applications.
Conclusion
PHP provides powerful numeric data types and built-in mathematical functions to perform different calculations. You can work with integers, floats, arithmetic operations, rounding, number formatting, random number generation, and mathematical calculations.
Understanding PHP numbers is important for developing calculators, billing applications, student result systems, and dynamic websites.
PHP Type Casting and Type Juggling – Type Conversion, Implicit Conversion and Explicit Conversion with Examples
PHP is a dynamically typed programming language. This means you do not need to declare the data type of a variable when creating it. PHP automatically determines the data type based on the assigned value.
Sometimes, you may need to convert one data type into another. This process is called Type Casting or Type Conversion.
In this tutorial, you will learn about PHP type casting, type juggling, implicit conversion, explicit conversion, and type checking with practical examples.
1. What is Type Casting in PHP?
Type casting means converting a variable from one data type into another data type.
For example:
String to Integer
Integer to Float
Float to Integer
Integer to String
String to Boolean
Example:
<?php
$num = "100";
$convertedNum = (int)$num;
echo $convertedNum;
echo "<br>";
var_dump($convertedNum);
?>Output:
100
int(100)In this example, the string "100" is converted into an integer using (int).
2. Types of Type Conversion in PHP
PHP supports two main types of type conversion:
Implicit Type Conversion (Type Juggling)
Explicit Type Conversion (Type Casting)
Let's understand both types.
3. Implicit Type Conversion in PHP
Implicit type conversion happens automatically when PHP converts a value from one data type to another during an operation.
You do not need to manually specify the data type.
Example:
<?php
$a = 10;
$b = 5.5;
$result = $a + $b;
echo $result;
echo "<br>";
var_dump($result);
?>Output:
15.5
float(15.5)Here:
$acontains an integer.$bcontains a float.PHP automatically converts the integer into a float for the calculation.
The result is a float.
4. Explicit Type Conversion in PHP
Explicit type conversion means manually converting a variable into another data type using a type cast or conversion function.
Example:
<?php
$num = 25.75;
$convertedNum = (int)$num;
echo $convertedNum;
echo "<br>";
var_dump($convertedNum);
?>Output:
25
int(25)Here, the float value 25.75 is converted into an integer. The decimal part is removed.
5. PHP Type Casting Operators
PHP provides different casting operators to convert values into specific data types.
Casting Operator | Description | Example |
|---|---|---|
| Converts to Integer |
|
| Converts to Integer |
|
| Converts to Float |
|
| Converts to Float |
|
| Converts to String |
|
| Converts to Boolean |
|
| Converts to Array |
|
| Converts to Object |
|
| Deprecated in PHP 8.0 | Do not use |
Note: (unset) casting was deprecated in PHP 7.2 and removed in PHP 8.0. Use null when you need a null value.
6. Convert String to Integer in PHP
You can convert a numeric string into an integer using (int) or (integer).
Example:
<?php
$value = "500";
$result = (int)$value;
echo $result;
echo "<br>";
var_dump($result);
?>Output:
500
int(500)7. Convert String to Float in PHP
You can convert a numeric string into a floating-point number using (float).
Example:
<?php
$value = "150.75";
$result = (float)$value;
echo $result;
echo "<br>";
var_dump($result);
?>Output:
150.75
float(150.75)8. Convert Integer to String in PHP
You can convert an integer into a string using (string).
Example:
<?php
$number = 100;
$result = (string)$number;
echo $result;
echo "<br>";
var_dump($result);
?>Output:
100
string(3) "100"9. Convert Float to Integer in PHP
You can convert a float into an integer using (int).
The decimal portion is discarded rather than rounded.
Example:
<?php
$price = 199.99;
$result = (int)$price;
echo $result;
echo "<br>";
var_dump($result);
?>Output:
199
int(199)10. Convert Integer to Float in PHP
You can convert an integer into a float using (float).
Example:
<?php
$number = 100;
$result = (float)$number;
echo $result;
echo "<br>";
var_dump($result);
?>Output:
100
float(100)11. Convert Value to Boolean in PHP
You can convert a value into a Boolean using (bool).
PHP considers the following values as false:
false00.0""(empty string)"0"(string containing zero)null
Other values are generally considered true.
Example:
<?php
$a = 1;
$b = 0;
$c = "Hello";
$d = "";
var_dump((bool)$a);
echo "<br>";
var_dump((bool)$b);
echo "<br>";
var_dump((bool)$c);
echo "<br>";
var_dump((bool)$d);
?>Output:
bool(true)
bool(false)
bool(true)
bool(false)12. Convert Value to Array in PHP
You can convert a value into an array using (array).
Example:
<?php
$number = 100;
$result = (array)$number;
print_r($result);
?>Output:
Array
(
[0] => 100
)For a scalar value, PHP creates an array with one element.
13. Convert Value to Object in PHP
You can convert a value into an object using (object).
Example:
<?php
$number = 100;
$result = (object)$number;
var_dump($result);
?>Output:
object(stdClass)#1 (1) {
["scalar"] =>
int(100)
}When a scalar is cast to an object, PHP creates a stdClass object with a property named scalar.
14. What is Type Juggling in PHP?
Type juggling is PHP's automatic handling of data types during certain operations.
PHP may automatically convert values to compatible types depending on the operation.
Example:
<?php
$a = "100";
$b = 50;
$result = $a + $b;
echo $result;
echo "<br>";
var_dump($result);
?>Output:
150
int(150)Here:
$acontains a numeric string.$bcontains an integer.PHP converts the numeric string into a number for the addition.
The result is an integer.
Important: Type juggling depends on the operation and PHP version. It is not the same as converting every variable permanently.
15. Convert Data Types Using PHP Conversion Functions
PHP also provides built-in functions that can be used to convert values.
Function | Description |
|---|---|
| Converts a value to an integer |
| Converts a value to a float |
| Converts a value to a string |
| Converts a value to a Boolean |
| Changes the type of a variable |
Example: intval()
<?php
$value = "250";
$result = intval($value);
echo $result;
echo "<br>";
var_dump($result);
?>Output:
250
int(250)Example: floatval()
<?php
$value = "99.50";
$result = floatval($value);
echo $result;
echo "<br>";
var_dump($result);
?>Output:
99.5
float(99.5)Example: strval()
<?php
$value = 500;
$result = strval($value);
echo $result;
echo "<br>";
var_dump($result);
?>Output:
500
string(3) "500"Example: boolval()
<?php
$value = 1;
$result = boolval($value);
var_dump($result);
?>Output:
bool(true)16. Change Variable Type Using settype()
The settype() function changes the data type of an existing variable.
Syntax:
settype(variable, type);Example:
<?php
$number = "100";
settype($number, "integer");
echo $number;
echo "<br>";
var_dump($number);
?>Output:
100
int(100)Important: Unlike a normal cast, settype() modifies the original variable.
17. Check Data Types Using PHP Functions
PHP provides several functions to check the data type of a variable.
Function | Description |
|---|---|
| Checks whether a value is an integer |
| Checks whether a value is a float |
| Checks whether a value is a string |
| Checks whether a value is Boolean |
| Checks whether a value is an array |
| Checks whether a value is an object |
| Checks whether a value is NULL |
| Checks whether a value is numeric |
Example:
<?php
$name = "Rehan";
$age = 25;
$price = 99.50;
$skills = ["PHP", "Java", "Flutter"];
var_dump(is_string($name));
echo "<br>";
var_dump(is_int($age));
echo "<br>";
var_dump(is_float($price));
echo "<br>";
var_dump(is_array($skills));
?>Output:
bool(true)
bool(true)
bool(true)
bool(true)18. Difference Between Type Casting and Type Juggling
Type Casting | Type Juggling |
|---|---|
Conversion is performed manually. | Conversion happens automatically. |
Uses casting operators or conversion functions. | PHP handles conversion during operations. |
Gives more control over conversion. | Depends on the operation and data types. |
Example: | Example: |
19. Difference Between == and === in PHP
PHP provides two operators for comparing values: loose comparison (==) and strict comparison (===).
Loose Comparison (==):
It compares values after performing type conversion when necessary.
Strict Comparison (===):
It compares both the value and the data type without type juggling.
Example:
<?php
$a = 100;
$b = "100";
var_dump($a == $b);
echo "<br>";
var_dump($a === $b);
?>Output:
bool(true)
bool(false)Explanation:
$a == $breturnstruebecause both values are equal after type conversion.$a === $breturnsfalsebecause one value is an integer and the other is a string.
20. Complete Practical Example – PHP Marks Calculator Using Type Casting
Let's create a practical example in which student marks are received as strings and converted into integers before calculating the total and percentage.
<?php
$studentName = "Rehan";
// Marks received as strings
$subject1 = "85";
$subject2 = "90";
$subject3 = "78";
$subject4 = "88";
$subject5 = "95";
// Convert strings into integers
$subject1 = (int)$subject1;
$subject2 = (int)$subject2;
$subject3 = (int)$subject3;
$subject4 = (int)$subject4;
$subject5 = (int)$subject5;
// Calculate total marks
$total = $subject1 + $subject2 + $subject3 + $subject4 + $subject5;
// Calculate percentage
$percentage = ($total / 500) * 100;
// Display result
echo "Student Name: " . $studentName;
echo "<br>";
echo "Total Marks: " . $total;
echo "<br>";
echo "Percentage: " . number_format($percentage, 2) . "%";
?>Output:
Student Result
Student Name: Rehan
Total Marks: 436
Percentage: 87.20%
This example demonstrates how type casting can be used when processing numeric values received as strings.
21. Advantages of Type Casting in PHP
Data Conversion: Convert one data type into another.
Accurate Calculations: Convert numeric strings before performing calculations.
Better Data Handling: Manage values received from forms and external sources.
Type Control: Specify the expected data type for an operation.
Improved Comparisons: Avoid unexpected results caused by automatic type conversion.
Application Development: Useful in billing systems, calculators, forms, and database applications.
Conclusion
PHP type casting and type juggling are important concepts for handling different data types. Type casting allows developers to manually convert values, while type juggling allows PHP to perform automatic conversions during operations.
By understanding (int), (float), (string), (bool), intval(), floatval(), settype(), and strict comparisons, you can write more reliable PHP programs.
PHP Date and Time – Date Formatting, Time Zones and Date Manipulation
PHP provides several built-in functions to work with dates and times. These functions allow developers to display the current date and time, format dates, calculate differences between dates, convert date strings, and manage time zones.
In this tutorial, you will learn how to work with dates and times in PHP using practical examples.
1. What is Date and Time in PHP?
Date and time functions in PHP are used to handle date-related operations such as:
Displaying the current date and time.
Formatting dates in different formats.
Getting the current timestamp.
Converting date strings into timestamps.
Adding or subtracting days, months, and years.
Finding the difference between two dates.
Setting the correct time zone.
PHP provides built-in functions such as date(), time(), strtotime(), and date_default_timezone_set().
2. PHP date() Function
The date() function is used to format and display the current date and time.
Syntax:
date(format, timestamp);Parameters:
format: Specifies the format in which the date should be displayed.timestamp: Optional. Specifies a timestamp. If omitted, the current date and time are used.
Example:
<?php
echo date("d-m-Y");
?>Output:
15-11-2026The output depends on the current date.
3. PHP Date Formatting Characters
PHP provides different formatting characters to display dates and times in various formats.
Date Formatting Characters
Character | Description | Example |
|---|---|---|
d | Day of the month (01–31) | 15 |
j | Day without leading zero | 5 |
D | Short day name | Sun |
l | Full day name | Sunday |
m | Month (01–12) | 11 |
n | Month without leading zero | 3 |
M | Short month name | Nov |
F | Full month name | November |
Y | Four-digit year | 2026 |
y | Two-digit year | 26 |
Example:
<?php
echo date("d-m-Y");
echo "<br>";
echo date("d/m/Y");
echo "<br>";
echo date("l, d F Y");
?>Output:
15-11-2026
15/11/2026
Sunday, 15 November 2026Time Formatting Characters
Character | Description | Example |
|---|---|---|
h | 12-hour format | 08 |
H | 24-hour format | 20 |
i | Minutes | 30 |
s | Seconds | 45 |
a | Lowercase am/pm | pm |
A | Uppercase AM/PM | PM |
g | 12-hour format without leading zero | 8 |
G | 24-hour format without leading zero | 20 |
Example:
<?php
echo date("h:i:s A");
echo "<br>";
echo date("H:i:s");
?>Output:
08:30:45 PM
20:30:45Note: The output shown above is an example. Actual output depends on the current time and configured time zone.
4. Display Current Date and Time
You can use the date() function to display the current date and time together.
Example:
<?php
echo "Current Date: " . date("d-m-Y");
echo "<br>";
echo "Current Time: " . date("h:i:s A");
echo "<br>";
echo "Current Date and Time: " . date("d-m-Y h:i:s A");
?>Example Output:
Current Date: 15-11-2026
Current Time: 12:30:45 AM
Current Date and Time: 15-11-2026 12:30:45 AM5. PHP time() Function
The time() function returns the current Unix timestamp.
A Unix timestamp represents the number of seconds that have passed since January 1, 1970, at 00:00:00 UTC.
Syntax:
time();Example:
<?php
$currentTime = time();
echo $currentTime;
?>Example Output:
1794700000The timestamp changes continuously, so your actual output will be different.
Convert Timestamp into a Readable Date
You can use the date() function to convert a timestamp into a readable date.
<?php
$timestamp = time();
echo date("d-m-Y H:i:s", $timestamp);
?>Example Output:
15-11-2026 00:30:456. PHP strtotime() Function
The strtotime() function converts an English textual date or time description into a Unix timestamp.
Syntax:
strtotime(datetime, baseTimestamp);Parameters:
datetime: A date or time string.baseTimestamp: Optional. The timestamp used as the base for relative date calculations.
Example:
<?php
$date = strtotime("15 November 2026");
echo date("d-m-Y", $date);
?>Output:
15-11-2026Using Relative Dates
You can also use strtotime() with relative date expressions.
<?php
echo date("d-m-Y", strtotime("tomorrow"));
echo "<br>";
echo date("d-m-Y", strtotime("yesterday"));
echo "<br>";
echo date("d-m-Y", strtotime("+7 days"));
echo "<br>";
echo date("d-m-Y", strtotime("+1 month"));
echo "<br>";
echo date("d-m-Y", strtotime("-1 year"));
?>Output: The results depend on the current date.
7. PHP date_default_timezone_set() Function
The date_default_timezone_set() function sets the default time zone for date and time functions in PHP.
By default, PHP may use a different time zone depending on its configuration.
For India, you can set the time zone to Asia/Kolkata.
Syntax:
date_default_timezone_set(timezone);Example:
<?php
date_default_timezone_set("Asia/Kolkata");
echo "Current Date: " . date("d-m-Y");
echo "<br>";
echo "Current Time: " . date("h:i:s A");
?>Example Output:
Current Date: 15-11-2026
Current Time: 12:30:45 AMSetting the time zone ensures that PHP date and time functions use the selected time zone.
8. Get the Current Time Zone
You can use the date_default_timezone_get() function to get the currently configured default time zone.
Example:
<?php
date_default_timezone_set("Asia/Kolkata");
echo date_default_timezone_get();
?>Output:
Asia/Kolkata9. PHP DateTime Class
PHP also provides the DateTime class for working with dates and times using object-oriented programming.
It is useful for creating, modifying, comparing, and formatting dates.
Example:
<?php
$date = new DateTime();
echo $date->format("d-m-Y");
?>Example Output:
15-11-2026Format DateTime Using Different Formats
<?php
$date = new DateTime();
echo $date->format("d-m-Y");
echo "<br>";
echo $date->format("l, F d, Y");
echo "<br>";
echo $date->format("h:i:s A");
?>Example Output:
15-11-2026
Sunday, November 15, 2026
12:30:45 AM10. Add Days, Months and Years to a Date
The modify() method of the DateTime class allows you to add or subtract time from a date.
Example: Add 7 Days
<?php
$date = new DateTime("2026-11-15");
$date->modify("+7 days");
echo $date->format("d-m-Y");
?>Output:
22-11-2026Example: Add 1 Month
<?php
$date = new DateTime("2026-11-15");
$date->modify("+1 month");
echo $date->format("d-m-Y");
?>Output:
15-12-2026Example: Subtract 1 Year
<?php
$date = new DateTime("2026-11-15");
$date->modify("-1 year");
echo $date->format("d-m-Y");
?>Output:
15-11-202511. PHP DateInterval Class
The DateInterval class represents a date or time interval. You can use it with the DateTime class to add or subtract time.
Example:
<?php
$date = new DateTime("2026-11-15");
$interval = new DateInterval("P10D");
$date->add($interval);
echo $date->format("d-m-Y");
?>Output:
25-11-2026Here:
Prepresents a period.10Drepresents 10 days.
Some commonly used DateInterval formats:
Format | Meaning |
|---|---|
P1D | 1 day |
P7D | 7 days |
P1W | 1 week |
P1M | 1 month |
P1Y | 1 year |
PT1H | 1 hour |
PT30M | 30 minutes |
PT10S | 10 seconds |
12. Find Difference Between Two Dates
The diff() method is used to calculate the difference between two DateTime objects.
Example:
<?php
$date1 = new DateTime("2026-11-15");
$date2 = new DateTime("2026-11-25");
$difference = $date1->diff($date2);
echo "Difference: " . $difference->days . " days";
?>Output:
Difference: 10 daysYou can also display the difference in years, months, and days.
<?php
$date1 = new DateTime("2026-01-01");
$date2 = new DateTime("2026-11-15");
$difference = $date1->diff($date2);
echo $difference->y . " Years ";
echo $difference->m . " Months ";
echo $difference->d . " Days";
?>Output:
0 Years 10 Months 14 Days13. Compare Two Dates in PHP
You can compare two DateTime objects using comparison operators.
Example:
<?php
$date1 = new DateTime("2026-11-15");
$date2 = new DateTime("2026-11-25");
if ($date1 < $date2) {
echo "Date 1 is earlier than Date 2";
} elseif ($date1 > $date2) {
echo "Date 1 is later than Date 2";
} else {
echo "Both dates are equal";
}
?>Output:
Date 1 is earlier than Date 214. Create a Custom Date Using DateTime
You can create a specific date instead of using the current date.
Example:
<?php
$date = new DateTime("2025-01-26");
echo "Date: " . $date->format("d-m-Y");
echo "<br>";
echo "Day: " . $date->format("l");
echo "<br>";
echo "Month: " . $date->format("F");
echo "<br>";
echo "Year: " . $date->format("Y");
?>Output:
Date: 26-01-2025
Day: Sunday
Month: January
Year: 202515. PHP Date and Time Functions – Quick Reference
Function / Method | Description |
|---|---|
| Formats a date and time |
| Returns the current Unix timestamp |
| Converts a textual date into a timestamp |
| Sets the default time zone |
| Gets the default time zone |
| Returns date and time information as an array |
| Checks whether a date is valid |
| Creates a Unix timestamp |
| Creates a date and time object |
| Formats a DateTime object |
| Modifies a date |
| Adds a date interval |
| Subtracts a date interval |
| Calculates the difference between dates |
16. Practical Example – Display Current Date, Time and Future Date
Let's create a practical PHP program that displays the current date, current time, tomorrow's date, and the date after seven days.
Complete Code:
<?php
date_default_timezone_set("Asia/Kolkata");
$currentDate = new DateTime();
echo "<h2>PHP Date and Time Example</h2>";
echo "Current Date: ";
echo $currentDate->format("d-m-Y");
echo "<br><br>";
echo "Current Time: ";
echo $currentDate->format("h:i:s A");
echo "<br><br>";
$tomorrow = clone $currentDate;
$tomorrow->modify("+1 day");
echo "Tomorrow's Date: ";
echo $tomorrow->format("d-m-Y");
echo "<br><br>";
$nextWeek = clone $currentDate;
$nextWeek->modify("+7 days");
echo "After 7 Days: ";
echo $nextWeek->format("d-m-Y");
?>Example Output:
PHP Date and Time Example
Current Date: 15-11-2026
Current Time: 12:30:45 AM
Tomorrow's Date: 16-11-2026
After 7 Days: 22-11-2026Explanation:
date_default_timezone_set()sets the time zone to India.new DateTime()creates an object containing the current date and time.format()displays the date and time in the required format.clonecreates a separate copy of the original date object.modify("+1 day")adds one day to the date.modify("+7 days")adds seven days to the date.
17. Important Points to Remember
Use
date()to format and display dates.Use
time()to get the current Unix timestamp.Use
strtotime()to convert textual date expressions into timestamps.Use
date_default_timezone_set()to configure the correct time zone.Use the
DateTimeclass for advanced date and time operations.Use
diff()to calculate the difference between two dates.Use
modify()to add or subtract days, months, and years.Use
checkdate()to validate a calendar date.For applications that work with multiple time zones, consider using
DateTimeZoneandDateTimeImmutable.
Conclusion
PHP provides powerful built-in date and time functions that make it easy to manage dates, times, timestamps, and time zones. By understanding functions such as date(), time(), strtotime(), and the DateTime class, you can perform date-related operations in real-world PHP applications.
These concepts are useful when developing attendance systems, employee management systems, billing applications, booking systems, and other dynamic websites.
PHP Include and Require – How to Use include, require, include_once and require_once
PHP provides include and require statements to reuse code from one PHP file inside another PHP file.
Instead of writing the same code repeatedly on multiple pages, you can create separate files for common elements such as headers, footers, navigation menus, database connections, and configuration settings.
In this tutorial, you will learn how to use include, require, include_once, and require_once with practical examples.
1. What is Include and Require in PHP?
In PHP, include and require are used to insert the contents of one PHP file into another PHP file.
For example, suppose you have a website with 10 pages. Every page needs the same header and footer.
Instead of writing the header and footer code on every page, you can create separate files:
header.phpfooter.php
Then include these files wherever required.
Benefits of Include and Require:
Avoids code duplication.
Makes code reusable.
Makes projects easier to maintain.
Helps organize large PHP projects.
Allows common database connection files to be reused.
Makes it easier to update common website components.
2. PHP include Statement
The include statement inserts the content of one PHP file into another PHP file.
If the specified file cannot be found or opened, PHP generates a warning, but the script generally continues executing.
Syntax:
include 'filename.php';Example:
Create two PHP files.
File 1: message.php
<?php
echo "Welcome to LearnWithRehan!";
?>File 2: index.php
<?php
include 'message.php';
echo "<br>";
echo "This is the main PHP page.";
?>Output:
Welcome to LearnWithRehan!
This is the main PHP page.Explanation:
We created a file named
message.php.Inside that file, we wrote a welcome message.
In
index.php, we usedinclude 'message.php';.PHP inserted and executed the contents of
message.php.The remaining code in
index.phpalso executed.
3. PHP require Statement
The require statement is also used to insert one PHP file into another PHP file.
The main difference is that if the required file cannot be found or opened, PHP generates an error and stops normal script execution at that point.
Syntax:
require 'filename.php';Example:
File 1: config.php
<?php
$websiteName = "LearnWithRehan";
?>File 2: index.php
<?php
require 'config.php';
echo "Welcome to " . $websiteName;
?>Output:
Welcome to LearnWithRehanExplanation:
We created a file named
config.php.We declared a variable
$websiteName.In
index.php, we used therequirestatement.PHP loaded the contents of
config.php.We accessed the variable declared in that file.
4. Difference Between include and require
Both statements are used to reuse PHP files, but they behave differently when the specified file cannot be loaded.
Feature | include | require |
|---|---|---|
Purpose | Includes another PHP file | Includes another PHP file |
File not found | Generates a warning | Generates an error |
Script execution | Generally continues | Stops normal execution |
Best use | Optional files | Essential files |
Example |
|
|
Example: Using include
<?php
include 'test.php';
echo "This statement will execute.";
?>If test.php does not exist, PHP generates a warning, but the final echo statement generally executes.
Example: Using require
<?php
require 'test.php';
echo "This statement will execute.";
?>If test.php does not exist, PHP generates an error and the final echo statement will not execute.
5. PHP include_once Statement
The include_once statement works like include, but it ensures that the same file is included only once during a single script execution.
If the file has already been included, PHP will not include it again.
Syntax:
include_once 'filename.php';Example:
File 1: message.php
<?php
echo "LearnWithRehan PHP Tutorial<br>";
?>File 2: index.php
<?php
include_once 'message.php';
include_once 'message.php';
include_once 'message.php';
?>Output:
LearnWithRehan PHP TutorialExplanation:
Although we called include_once three times, PHP included and executed the file only once.
6. PHP require_once Statement
The require_once statement works like require, but it ensures that the same file is required only once during a single script execution.
It is especially useful for essential files such as database connections and configuration files.
Syntax:
require_once 'filename.php';Example:
File 1: database.php
<?php
$serverName = "localhost";
$databaseName = "my_database";
echo "Database configuration loaded.<br>";
?>File 2: index.php
<?php
require_once 'database.php';
require_once 'database.php';
require_once 'database.php';
echo "Main page executed.";
?>Output:
Database configuration loaded.
Main page executed.Explanation:
The first
require_onceloadsdatabase.php.The second and third calls do not load the file again.
The main page continues executing.
7. Difference Between include_once and require_once
Feature | include_once | require_once |
|---|---|---|
Purpose | Includes a file once | Requires a file once |
Duplicate inclusion | Prevented | Prevented |
File not found | Generates a warning | Generates an error |
Script execution | Generally continues | Stops normal execution |
Best use | Optional files | Essential files |
8. Practical Example – Create a Website Using Include
Let's create a simple website using separate header, navigation, content, and footer files.
Project Structure:
PHP_Project/
│
├── index.php
├── header.php
├── navbar.php
├── content.php
└── footer.phpStep 1: Create header.php
<!DOCTYPE html>
<html>
<head>
<title>LearnWithRehan</title>
</head>
<body>
<h1>Welcome to LearnWithRehan</h1>
<hr>Step 2: Create navbar.php
<nav>
<a href="index.php">Home</a> |
<a href="#">About</a> |
<a href="#">Contact</a>
</nav>
<hr>Step 3: Create content.php
<h2>Home Page</h2>
<p>
Welcome to LearnWithRehan.
Learn PHP, Java, Android, Flutter and more
programming tutorials.
</p>Step 4: Create footer.php
<hr>
<footer>
<p>Copyright © 2026 LearnWithRehan</p>
</footer>
</body>
</html>Step 5: Create index.php
<?php
include 'header.php';
include 'navbar.php';
include 'content.php';
include 'footer.php';
?>Output:
Welcome to LearnWithRehan
Home
|
About
|
Contact
Home Page
Welcome to LearnWithRehan. Learn PHP, Java, Android, Flutter and more programming tutorials.
Copyright © 2026 LearnWithRehanExplanation:
header.phpcontains the website header.navbar.phpcontains the navigation menu.content.phpcontains the main page content.footer.phpcontains the footer.index.phpcombines all these files usinginclude.
This approach makes website development easier because you can reuse the same header, navigation menu, and footer on multiple pages.
9. Practical Example – Reuse a Database Connection File
In real-world PHP projects, database connection code is usually stored in a separate file.
You can reuse that file on different pages using require_once.
File 1: db_connection.php
<?php
$serverName = "localhost";
$connectionOptions = array(
"Database" => "my_database",
"Uid" => "your_username",
"PWD" => "your_password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
echo "Database Connected Successfully.";
?>File 2: index.php
<?php
require_once 'db_connection.php';
// Write your database operations here.
?>Explanation:
We created a separate database connection file.
We established a SQL Server connection using
sqlsrv_connect().We loaded the connection file using
require_once.Now the
$connvariable is available in the main PHP file.We can reuse this connection for database operations.
Note: This example uses the Microsoft SQLSRV PHP extension. You must configure it and replace the database credentials with your own.
10. Difference Between All Four Statements
Statement | Loads file | Prevents duplicate loading | Missing file behavior |
|---|---|---|---|
| Yes | No | Warning |
| Yes | No | Error |
| Yes | Yes | Warning |
| Yes | Yes | Error |
11. Important Points to Remember
includeis used to insert another PHP file into the current file.requireis used when the file is essential for the application.include_onceprevents the same file from being included multiple times.require_onceprevents the same required file from being loaded multiple times.Use
require_oncefor important files such as database connections and configuration files.Use relative or absolute paths carefully to avoid file path errors.
Included PHP files can access variables from the scope in which they are included.
Conclusion
PHP include and require statements help developers create reusable and maintainable applications. Instead of writing the same code repeatedly, you can divide your project into multiple files and load them wherever needed.
PHP Forms – GET and POST Methods, Form Handling and Data Validation
PHP forms are used to collect information from users and process that information on the server. For example, login forms, registration forms, contact forms, feedback forms, and search forms are commonly created using PHP.
PHP supports two commonly used HTTP methods for submitting form data:
GET Method
POST Method
In this tutorial, you will learn how to create HTML forms, receive form data in PHP, use GET and POST methods, validate user input, and build a practical registration form.
1. What is a PHP Form?
A PHP form is an HTML form that sends user-entered information to a PHP script for processing.
For example, suppose you want to create a registration form that collects:
User Name
Email Address
Mobile Number
Password
When a user submits the form, PHP receives the submitted information and processes it.
Basic HTML Form:
<!DOCTYPE html>
<html>
<head>
<title>PHP Form Example</title>
</head>
<body>
<h2>Registration Form</h2>
<form method="POST" action="process.php">
Name:
<input type="text" name="username">
<br><br>
Email:
<input type="email" name="email">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>Explanation:
<form>creates an HTML form.method="POST"specifies the form submission method.action="process.php"specifies the PHP file that will receive the submitted data.name="username"identifies the input field.The submit button sends the form data to the server.
2. PHP GET Method
The GET method is used to send form data through URL parameters.
When you submit a form using GET, the submitted information becomes visible in the browser's URL.
PHP provides the $_GET superglobal array to access GET request data.
Syntax:
$_GET["field_name"];Example:
Create a file named get_form.php.
<!DOCTYPE html>
<html>
<head>
<title>GET Method</title>
</head>
<body>
<h2>GET Method Example</h2>
<form method="GET" action="get_process.php">
Enter Your Name:
<input type="text" name="username">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>Now create another file named get_process.php.
<?php
if (isset($_GET["username"])) {
$name = $_GET["username"];
echo "Welcome " . htmlspecialchars($name);
}
?>Example Output:
Welcome RehanAfter submitting the form, the URL will look similar to this:
http://localhost/get_process.php?username=RehanExplanation:
The user enters their name in the input field.
The form submits data using the GET method.
PHP receives the information through
$_GET.isset()checks whether the submitted parameter exists.htmlspecialchars()safely displays the user's input as HTML text.
Important Points About GET Method
Form data is visible in the URL.
It is useful for search forms and filters.
Data can be bookmarked and shared through URLs.
It is not suitable for passwords or sensitive information.
URLs have practical length limitations.
3. PHP POST Method
The POST method sends form data in the HTTP request body instead of placing it in the URL.
PHP provides the $_POST superglobal array to access POST request data.
Syntax:
$_POST["field_name"];Example:
Create a file named post_form.php.
<!DOCTYPE html>
<html>
<head>
<title>POST Method</title>
</head>
<body>
<h2>POST Method Example</h2>
<form method="POST" action="post_process.php">
Enter Your Name:
<input type="text" name="username">
<br><br>
Enter Your Email:
<input type="email" name="email">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>Create another file named post_process.php.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"] ?? "";
$email = $_POST["email"] ?? "";
echo "Name: " . htmlspecialchars($name);
echo "<br>";
echo "Email: " . htmlspecialchars($email);
}
?>Example Output:
Name: Rehan
Email: rehan@example.comExplanation:
The user enters their name and email.
The form submits the information using POST.
PHP receives the information through
$_POST.$_SERVER["REQUEST_METHOD"]checks the request method.htmlspecialchars()safely displays the submitted values.
Important Points About POST Method
Form data is not displayed in the URL.
It is suitable for registration and login forms.
It can send larger amounts of data than GET, subject to server and application limits.
It supports file uploads when configured correctly.
POST does not automatically encrypt information. Use HTTPS to protect data during transmission.
4. Difference Between GET and POST Methods
Feature | GET Method | POST Method |
|---|---|---|
Data location | URL parameters | Request body |
PHP superglobal |
|
|
Data visibility | Visible in URL | Not visible in URL |
Bookmarking | Can bookmark submitted URL | Submitted body is not bookmarked |
Sensitive data | Not suitable | Better than GET, but requires HTTPS |
File uploads | Not normally used | Supported with correct form configuration |
Common use | Search and filters | Registration and login |
5. What are PHP Superglobal Variables?
Superglobal variables are predefined PHP variables that are available throughout a PHP script without requiring the global keyword.
PHP provides several superglobal arrays for accessing request data, server information, sessions, cookies, and more.
Some commonly used PHP superglobals are:
Superglobal | Description |
|---|---|
| Accesses GET request data |
| Accesses POST request data |
| Accesses GET, POST and cookie data, depending on configuration |
| Provides server and request information |
| Accesses uploaded file information |
| Stores session information |
| Accesses cookie information |
| Accesses environment variables |
| Accesses global variables |
Example:
<?php
echo "Request Method: " . $_SERVER["REQUEST_METHOD"];
echo "<br>";
echo "Server Name: " . $_SERVER["SERVER_NAME"];
?>Example Output:
Request Method: GET
Server Name: localhostThe actual request method depends on how the PHP page is accessed.
6. PHP Form Validation
Form validation means checking the information entered by a user before processing it.
For example:
Name should not be empty.
Email should be in a valid format.
Mobile number should contain the required number of digits.
Password should meet minimum length requirements.
Validation helps prevent incorrect or incomplete data from being processed.
Required Field Validation
You can use the empty() function to check whether a field is empty.
Example:
<?php
$name = "";
if (empty($name)) {
echo "Name is required.";
} else {
echo "Welcome " . htmlspecialchars($name);
}
?>Output:
Name is required.Email Validation
PHP provides the filter_var() function to validate email addresses.
Example:
<?php
$email = "rehan@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email Address";
} else {
echo "Invalid Email Address";
}
?>Output:
Valid Email AddressNumber Validation
You can use is_numeric() to check whether a value is numeric.
Example:
<?php
$mobile = "9876543210";
if (is_numeric($mobile)) {
echo "Valid Numeric Value";
} else {
echo "Please Enter Numbers Only";
}
?>Output:
Valid Numeric ValueNote that is_numeric() checks whether a value is numeric; it does not verify whether it is a valid mobile number.
7. PHP trim() Function in Form Handling
The trim() function removes whitespace from the beginning and end of a string.
It is useful when processing form data because users sometimes enter unnecessary spaces.
Example:
<?php
$name = " Rehan Khan ";
$name = trim($name);
echo $name;
?>Output:
Rehan Khan8. PHP htmlspecialchars() Function
The htmlspecialchars() function converts special HTML characters into HTML entities.
It helps prevent user-entered text from being interpreted as HTML or JavaScript when displayed on a webpage.
Example:
<?php
$message = "<h2>Hello Rehan</h2>";
echo htmlspecialchars($message);
?>Output:
<h2>Hello Rehan</h2>The browser displays the HTML characters as text instead of creating an actual heading.
Important: Use htmlspecialchars() when displaying untrusted text in HTML. It is not a replacement for SQL parameterized queries or other security measures.
9. Complete Practical Example – PHP Registration Form
Now let's create a registration form that accepts a user's name, email, mobile number, and password.
The form will:
Accept user information.
Check required fields.
Validate the email address.
Validate the mobile number.
Check password length.
Display the submitted information safely.
Project Structure:
PHP_Project/
│
└── registration.phpComplete Code: registration.php
<?php
$name = "";
$email = "";
$mobile = "";
$password = "";
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get Form Data
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$mobile = trim($_POST["mobile"] ?? "");
$password = $_POST["password"] ?? "";
// Validate Name
if ($name == "") {
$errors[] = "Name is required.";
}
// Validate Email
if ($email == "") {
$errors[] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Please enter a valid email address.";
}
// Validate Mobile Number
if (!preg_match("/^[0-9]{10}$/", $mobile)) {
$errors[] = "Mobile number must contain exactly 10 digits.";
}
// Validate Password
if (strlen($password) < 8) {
$errors[] = "Password must contain at least 8 characters.";
}
// Display Result
if (empty($errors)) {
echo "<h2>Registration Successful!</h2>";
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
echo "Mobile: " . htmlspecialchars($mobile) . "<br>";
echo "Password: Registration password accepted.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Registration Form</title>
</head>
<body>
<h2>Registration Form</h2>
<?php
if (!empty($errors)) {
foreach ($errors as $error) {
echo "<p style='color:red;'>"
. htmlspecialchars($error)
. "</p>";
}
}
?>
<form method="POST" action="">
Name:
<input type="text" name="name"
value="<?php echo htmlspecialchars($name); ?>">
<br><br>
Email:
<input type="email" name="email"
value="<?php echo htmlspecialchars($email); ?>">
<br><br>
Mobile Number:
<input type="text" name="mobile"
value="<?php echo htmlspecialchars($mobile); ?>">
<br><br>
Password:
<input type="password" name="password">
<br><br>
<input type="submit" value="Register">
</form>
</body>
</html>Example Output – Registration Form
Registration Form
Rehan Khan
rehan@example.com
9876543210
••••••••
Illustrative form preview. The actual PHP form runs on your local or hosted PHP server.
Example Successful Result:
Registration Successful!
Name: Rehan Khan
Email: rehan@example.com
Mobile: 9876543210
Password: Registration password accepted.Explanation:
The form submits information using the POST method.
PHP receives the submitted information through
$_POST.trim()removes unnecessary spaces from text fields.filter_var()validates the email address.preg_match()checks whether the mobile number contains exactly 10 digits.strlen()checks the password length.The
$errorsarray stores validation errors.If there are no errors, PHP displays the registration result.
Security note: This example only demonstrates form validation. A real registration system must store passwords using password_hash(), verify them using password_verify(), use prepared SQL statements, and implement CSRF protection.
10. Important PHP Form Validation Functions
Function | Purpose |
|---|---|
| Checks whether a variable or array key exists and is not null |
| Checks whether a value is empty |
| Removes whitespace from both ends |
| Returns string length in bytes |
| Filters or validates data |
| Checks whether a value is numeric |
| Checks a string against a regular expression |
| Converts special HTML characters |
| Removes HTML and PHP tags from a string |
11. Important Points to Remember
HTML forms are used to collect information from users.
PHP uses
$_GETto access GET request data.PHP uses
$_POSTto access POST request data.GET displays submitted values in the URL.
POST sends submitted values in the request body.
Use server-side validation even if HTML validation is enabled.
Use
htmlspecialchars()when displaying untrusted data in HTML.Use prepared statements when inserting form data into a database.
Use HTTPS to protect data during transmission.
Never store plain-text passwords in a database.
Conclusion
PHP forms are an important part of dynamic website development. By using HTML forms with PHP's GET and POST methods, developers can collect and process user information.
Functions such as trim(), filter_var(), preg_match(), and htmlspecialchars() help validate and safely display form data.
Understanding PHP forms is essential for developing login systems, registration pages, contact forms, feedback systems, and database-driven web applications.
PHP File Handling – Create, Open, Read, Write, Append and Delete Files in PHP
PHP provides built-in file handling functions that allow developers to create, open, read, write, append, and delete files on a server.
File handling is useful when developing applications that need to store information in text files, generate reports, maintain logs, or manage uploaded files.
In this tutorial, you will learn how to perform different file operations in PHP with practical examples.
1. What is File Handling in PHP?
File handling in PHP means performing operations on files using PHP code.
For example, you can use PHP to:
Create a new text file.
Open an existing file.
Read data from a file.
Write data into a file.
Append new data to an existing file.
Delete a file.
Check whether a file exists.
Get file size and other information.
PHP provides several built-in functions for file handling, such as fopen(), fread(), fwrite(), fclose(), file_get_contents(), file_put_contents(), and unlink().
2. PHP fopen() Function
The fopen() function is used to open a file in PHP.
It can open an existing file or create a new file, depending on the selected file mode.
Syntax:
fopen(filename, mode);Parameters:
filename: Specifies the name or path of the file.mode: Specifies how the file should be opened.
Common File Opening Modes
Mode | Description |
|---|---|
| Opens a file for reading only. File must exist. |
| Opens a file for reading and writing. File must exist. |
| Opens a file for writing. Creates it if it does not exist and truncates it if it exists. |
| Opens a file for reading and writing. Creates it if needed and truncates existing content. |
| Opens a file for appending. Creates it if it does not exist. |
| Opens a file for reading and appending. Creates it if needed. |
| Creates a new file for writing. Fails if the file already exists. |
| Creates a new file for reading and writing. Fails if it already exists. |
Example:
<?php
$file = fopen("test.txt", "r");
if ($file) {
echo "File opened successfully.";
fclose($file);
} else {
echo "Unable to open file.";
}
?>Output:
File opened successfully.Note: The test.txt file must already exist because we are using r mode.
3. PHP fclose() Function
The fclose() function is used to close an opened file.
After completing file operations, it is good practice to close the file to release the associated resources.
Syntax:
fclose(file_handle);Example:
<?php
$file = fopen("test.txt", "r");
if ($file) {
echo "File opened successfully.";
fclose($file);
echo "<br>File closed successfully.";
}
?>Output:
File opened successfully.
File closed successfully.4. Create a File Using PHP
You can create a new file using the fopen() function with w or x mode.
wcreates a file if it does not exist. If it already exists, its previous contents are removed.xcreates a new file only if it does not already exist.
Example:
<?php
$file = fopen("myfile.txt", "w");
if ($file) {
echo "File created successfully.";
fclose($file);
} else {
echo "Unable to create file.";
}
?>Output:
File created successfully.A new file named myfile.txt will be created in the current working directory if it does not already exist.
5. PHP fwrite() Function
The fwrite() function is used to write data into an opened file.
Syntax:
fwrite(file_handle, data);Example:
<?php
$file = fopen("myfile.txt", "w");
if ($file) {
fwrite($file, "Welcome to LearnWithRehan!");
fclose($file);
echo "Data written successfully.";
}
?>Output:
Data written successfully.Content of myfile.txt:
Welcome to LearnWithRehan!Explanation:
fopen()opens the file in write mode.fwrite()writes the specified text into the file.fclose()closes the file.
Important: When you use w mode, existing content is removed before writing new data.
6. PHP fread() Function
The fread() function is used to read data from an opened file.
It requires a file handle and the number of bytes to read.
Syntax:
fread(file_handle, length);Example:
Suppose myfile.txt contains:
Welcome to LearnWithRehan!PHP Code:
<?php
$file = fopen("myfile.txt", "r");
if ($file) {
$data = fread($file, filesize("myfile.txt"));
echo $data;
fclose($file);
}
?>Output:
Welcome to LearnWithRehan!Explanation:
fopen()opens the file in read mode.filesize()returns the file size in bytes.fread()reads the specified number of bytes.fclose()closes the file.
Note: If the file is empty, filesize() returns zero. For reading complete files, file_get_contents() is often simpler.
7. PHP file_get_contents() Function
The file_get_contents() function reads the entire contents of a file into a string.
It is one of the easiest ways to read a text file in PHP.
Syntax:
file_get_contents(filename);Example:
<?php
$data = file_get_contents("myfile.txt");
echo $data;
?>Output:
Welcome to LearnWithRehan!Explanation:
file_get_contents()opens and reads the file.The complete file content is stored in the
$datavariable.echodisplays the content.
8. PHP file_put_contents() Function
The file_put_contents() function writes data into a file.
If the file does not exist, PHP creates it automatically.
If the file already exists, its previous contents are overwritten by default.
Syntax:
file_put_contents(filename, data, flags);Example:
<?php
$data = "PHP File Handling Tutorial";
$result = file_put_contents("myfile.txt", $data);
if ($result !== false) {
echo "File data saved successfully.";
} else {
echo "Unable to save file.";
}
?>Output:
File data saved successfully.Content of myfile.txt:
PHP File Handling Tutorial9. Append Data to a File in PHP
Appending means adding new data at the end of an existing file without removing its previous content.
You can use the FILE_APPEND flag with file_put_contents().
Example:
<?php
$data = "\nWelcome to LearnWithRehan!";
$result = file_put_contents(
"myfile.txt",
$data,
FILE_APPEND
);
if ($result !== false) {
echo "Data appended successfully.";
}
?>Output:
Data appended successfully.Content of myfile.txt:
PHP File Handling Tutorial
Welcome to LearnWithRehan!Alternatively, you can use fopen() with a mode and fwrite().
<?php
$file = fopen("myfile.txt", "a");
fwrite($file, "\nNew PHP Tutorial Added.");
fclose($file);
echo "New data added successfully.";
?>10. PHP file_exists() Function
The file_exists() function checks whether a file or directory exists.
It returns true if the specified path exists and false otherwise.
Syntax:
file_exists(filename);Example:
<?php
if (file_exists("myfile.txt")) {
echo "File exists.";
} else {
echo "File does not exist.";
}
?>Output:
File exists.11. PHP filesize() Function
The filesize() function returns the size of a file in bytes.
Example:
<?php
if (file_exists("myfile.txt")) {
$size = filesize("myfile.txt");
echo "File Size: " . $size . " bytes";
}
?>Example Output:
File Size: 58 bytesThe actual size depends on the content of your file.
12. PHP unlink() Function
The unlink() function is used to delete a file from the server.
Syntax:
unlink(filename);Example:
<?php
if (file_exists("myfile.txt")) {
if (unlink("myfile.txt")) {
echo "File deleted successfully.";
} else {
echo "Unable to delete file.";
}
} else {
echo "File does not exist.";
}
?>Output:
File deleted successfully.Important: The unlink() function permanently removes the specified file from its location. Always verify the file path before deleting anything.
13. PHP is_readable() and is_writable() Functions
PHP provides functions to check file permissions.
is_readable()
Checks whether a file exists and can be read by the current process.
<?php
if (is_readable("myfile.txt")) {
echo "File is readable.";
} else {
echo "File is not readable.";
}
?>is_writable()
Checks whether a file exists and can be written to by the current process.
<?php
if (is_writable("myfile.txt")) {
echo "File is writable.";
} else {
echo "File is not writable.";
}
?>14. PHP file() Function
The file() function reads an entire file into an array, with each line stored as a separate array element.
Example:
Suppose students.txt contains:
Rehan
Amit
Rahul
PriyaPHP Code:
<?php
$students = file("students.txt");
foreach ($students as $student) {
echo htmlspecialchars(trim($student)) . "<br>";
}
?>Output:
Rehan
Amit
Rahul
Priya15. PHP copy() and rename() Functions
PHP also provides functions to copy and rename files.
copy() Function
The copy() function creates a copy of an existing file.
Syntax:
copy(source, destination);Example:
<?php
if (copy("myfile.txt", "backup.txt")) {
echo "File copied successfully.";
} else {
echo "Unable to copy file.";
}
?>Output:
File copied successfully.rename() Function
The rename() function changes the name of a file or moves it to another location.
Syntax:
rename(old_name, new_name);Example:
<?php
if (rename("backup.txt", "new_backup.txt")) {
echo "File renamed successfully.";
} else {
echo "Unable to rename file.";
}
?>Output:
File renamed successfully.16. Practical Example – Create a Simple Student Record File
Let's create a practical PHP application that accepts student information and saves it in a text file.
The application will:
Accept student name.
Accept student email.
Save the information in a text file.
Display a success message.
Read and display saved student records.
Project Structure:
PHP_Project/
│
├── student.php
└── students.txtComplete Code: student.php
<?php
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name == "" || $email == "") {
$message = "All fields are required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$message = "Please enter a valid email address.";
} else {
// Prepare Student Data
$record = "Name: " . $name .
" | Email: " . $email .
PHP_EOL;
// Save Data in File
$result = file_put_contents(
"students.txt",
$record,
FILE_APPEND | LOCK_EX
);
if ($result !== false) {
$message = "Student record saved successfully.";
} else {
$message = "Unable to save student record.";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Student Record System</title>
</head>
<body>
<h2>Student Registration</h2>
<p>
<?php echo htmlspecialchars($message); ?>
</p>
<form method="POST" action="">
Student Name:
<input type="text" name="name" required>
<br><br>
Student Email:
<input type="email" name="email" required>
<br><br>
<input type="submit" value="Save Record">
</form>
<hr>
<h2>Student Records</h2>
<?php
if (file_exists("students.txt")) {
$records = file("students.txt");
foreach ($records as $record) {
echo htmlspecialchars($record) . "<br>";
}
} else {
echo "No student records found.";
}
?>
</body>
</html>Example Output
Student Registration
Student Records
- Name: Rehan Khan | Email: rehan@example.com
Illustrative output of the PHP application.Explanation:
The HTML form accepts the student's name and email.
PHP receives the submitted values through
$_POST.trim()removes unnecessary spaces.filter_var()validates the email address.file_put_contents()saves the record instudents.txt.FILE_APPENDadds new records without removing existing records.LOCK_EXrequests an exclusive lock while writing.file()reads all saved records.htmlspecialchars()safely displays the records.
Important: This is a learning example. For a real student management system, use a database such as MySQL or SQL Server instead of storing records in a plain text file. Also, validate file paths and permissions carefully.
17. Important PHP File Handling Functions
Function | Description |
|---|---|
| Opens a file |
| Closes an opened file |
| Reads data from a file |
| Writes data into a file |
| Reads the entire file into a string |
| Writes data into a file |
| Checks whether a file or directory exists |
| Returns file size in bytes |
| Deletes a file |
| Reads a file into an array |
| Copies a file |
| Renames or moves a file |
| Checks whether a file is readable |
| Checks whether a file is writable |
18. Important Points to Remember
Use
fopen()to open or create files.Use
fread()to read file content.Use
fwrite()to write data into files.Use
fclose()to close opened file handles.Use
file_get_contents()to read an entire file.Use
file_put_contents()to write data into a file.Use
FILE_APPENDto add new data without overwriting existing content.Use
file_exists()to check whether a file exists.Use
unlink()to delete a file.Always validate file paths and permissions before performing file operations.
Never allow users to freely specify server file paths without proper validation.
Conclusion
PHP File Handling allows developers to manage files directly from PHP applications. Using functions such as fopen(), fread(), fwrite(), file_get_contents(), file_put_contents(), and unlink(), you can create, read, update, and delete files.
These concepts are useful for creating log files, generating reports, storing simple records, managing text files, and handling application data.
PHP File Upload – How to Upload Images and Documents Using PHP
PHP provides built-in functionality to upload files from a user's computer to a web server.
File upload functionality is commonly used in registration forms, profile management systems, document management applications, educational websites, and admin panels.
For example, a user can upload:
Profile pictures.
Student photographs.
PDF documents.
Word documents.
Excel files.
Product images.
Certificates and other documents.
In this tutorial, you will learn how to create a file upload form, access uploaded files using $_FILES, validate file types and sizes, upload images, and build a practical PHP file upload application.
1. What is File Upload in PHP?
File upload in PHP means transferring a file from a user's computer to a server using an HTML form and PHP code.
PHP provides a predefined superglobal array called $_FILES to access information about uploaded files.
Basic File Upload Process:
Create an HTML form with a file input field.
Set the form method to
POST.Set
enctype="multipart/form-data".Select a file from the computer.
Submit the form.
PHP receives the uploaded file through
$_FILES.Validate the file.
Move the file to the desired server directory.
2. Create an HTML File Upload Form
To upload files using PHP, you must create an HTML form with the input element having type="file".
The form must also include the enctype="multipart/form-data" attribute.
Example:
<!DOCTYPE html>
<html>
<head>
<title>PHP File Upload</title>
</head>
<body>
<h2>Upload Your File</h2>
<form method="POST"
action="upload.php"
enctype="multipart/form-data">
Select File:
<input type="file" name="myfile">
<br><br>
<input type="submit" value="Upload File">
</form>
</body>
</html>Explanation:
method="POST"sends the form data using the POST method.action="upload.php"specifies the PHP file that processes the upload.enctype="multipart/form-data"allows the form to send file data.type="file"creates a file selection field.name="myfile"identifies the uploaded file in PHP.
Important: Without enctype="multipart/form-data", the browser will not submit the file contents correctly.
3. What is the PHP $_FILES Superglobal?
PHP provides the $_FILES superglobal array to access uploaded file information.
It contains details about the uploaded file, such as its name, temporary location, size, and upload status.
Syntax:
$_FILES["input_name"]["property"];Common $_FILES Properties
Property | Description |
|---|---|
| Original name of the uploaded file |
| MIME type reported by the browser |
| Temporary location of the uploaded file |
| Upload error code |
| Uploaded file size in bytes |
| Full path supplied by the browser, where supported |
Example:
<?php
if (isset($_FILES["myfile"])) {
echo "File Name: " . htmlspecialchars($_FILES["myfile"]["name"]);
echo "<br>";
echo "File Type: " . htmlspecialchars($_FILES["myfile"]["type"]);
echo "<br>";
echo "Temporary Name: " . htmlspecialchars($_FILES["myfile"]["tmp_name"]);
echo "<br>";
echo "File Size: " . $_FILES["myfile"]["size"] . " bytes";
echo "<br>";
echo "Upload Error: " . $_FILES["myfile"]["error"];
}
?>Example Output:
File Name: profile.jpg
File Type: image/jpeg
Temporary Name: C:\xampp\tmp\php1234.tmp
File Size: 245678 bytes
Upload Error: 0Note: The temporary location and file information depend on your server and selected file.
4. PHP move_uploaded_file() Function
The move_uploaded_file() function moves an uploaded file from its temporary location to a permanent location on the server.
PHP initially stores uploaded files in a temporary directory. To keep the file, you must move it to your desired directory.
Syntax:
move_uploaded_file(temp_file, destination);Parameters:
temp_file: Temporary location of the uploaded file.destination: Final location where the file should be stored.
Example:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fileName = $_FILES["myfile"]["name"];
$tempName = $_FILES["myfile"]["tmp_name"];
$destination = "uploads/" . basename($fileName);
if (move_uploaded_file($tempName, $destination)) {
echo "File uploaded successfully.";
} else {
echo "File upload failed.";
}
}
?>Output:
File uploaded successfully.Note: The uploads directory must already exist and be writable by the PHP process.
5. Complete Example – Upload a File Using PHP
Now let's create a simple file upload application.
Project Structure:
PHP_Project/
│
├── index.php
├── upload.php
│
└── uploads/Step 1: Create index.php
<!DOCTYPE html>
<html>
<head>
<title>PHP File Upload</title>
</head>
<body>
<h2>Upload Your File</h2>
<form method="POST"
action="upload.php"
enctype="multipart/form-data">
Select File:
<input type="file" name="myfile" required>
<br><br>
<input type="submit" value="Upload File">
</form>
</body>
</html>Step 2: Create upload.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_FILES["myfile"])) {
$fileName = $_FILES["myfile"]["name"];
$tempName = $_FILES["myfile"]["tmp_name"];
$fileSize = $_FILES["myfile"]["size"];
$fileError = $_FILES["myfile"]["error"];
if ($fileError === UPLOAD_ERR_OK) {
$destination = "uploads/" . basename($fileName);
if (move_uploaded_file($tempName, $destination)) {
echo "File uploaded successfully.";
echo "<br>";
echo "File Name: " . htmlspecialchars($fileName);
echo "<br>";
echo "File Size: " . $fileSize . " bytes";
} else {
echo "Unable to move uploaded file.";
}
} else {
echo "File upload error: " . $fileError;
}
}
}
?>Example Output:
File uploaded successfully.
File Name: profile.jpg
File Size: 245678 bytesThis example demonstrates the basic file upload process. For a real application, you should validate the file type, size, destination, and filename before saving it.
6. Validate File Size in PHP
It is important to restrict file size before uploading it to the server.
For example, suppose you want to allow files up to 2 MB.
You can check the uploaded file size using the size property of $_FILES.
Example:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fileSize = $_FILES["myfile"]["size"];
$maxSize = 2 * 1024 * 1024;
if ($fileSize <= $maxSize) {
echo "File size is valid.";
} else {
echo "File size must be less than 2 MB.";
}
}
?>Output:
File size is valid.Explanation:
1024bytes = 1 KB.1024 * 1024bytes = 1 MB.2 * 1024 * 1024bytes = 2 MB.
Important: PHP configuration settings such as upload_max_filesize and post_max_size also control the maximum upload size.
7. Validate File Extension in PHP
You can restrict which file extensions users are allowed to upload.
For example, if you want to allow only JPG, JPEG, and PNG images, you can check the file extension.
Example:
<?php
$fileName = $_FILES["myfile"]["name"];
$fileExtension = strtolower(
pathinfo($fileName, PATHINFO_EXTENSION)
);
$allowedExtensions = ["jpg", "jpeg", "png"];
if (in_array($fileExtension, $allowedExtensions, true)) {
echo "Valid file extension.";
} else {
echo "Only JPG, JPEG and PNG files are allowed.";
}
?>Output:
Valid file extension.Explanation:
pathinfo()extracts information about the file path.PATHINFO_EXTENSIONreturns the file extension.strtolower()converts the extension into lowercase.in_array()checks whether the extension exists in the allowed list.
Important: Extension checking alone is not sufficient for security. A user can rename another type of file with a .jpg extension.
8. Validate Image Type Using getimagesize()
PHP provides the getimagesize() function to inspect image information.
It can help determine whether a file contains a recognized image format.
Example:
<?php
$tmpName = $_FILES["myfile"]["tmp_name"];
$imageInfo = getimagesize($tmpName);
if ($imageInfo !== false) {
echo "Valid image file.";
} else {
echo "Invalid image file.";
}
?>Output:
Valid image file.For secure image uploads, also check the detected MIME type against an allowed list, limit image dimensions if needed, and generate a new server-side filename.
9. Upload Only JPG, JPEG and PNG Images
Now let's create a more secure image upload example with file extension checking, image validation, file size checking, and a generated filename.
Complete Code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_FILES["image"])) {
die("Please select an image.");
}
$file = $_FILES["image"];
// Check Upload Error
if ($file["error"] !== UPLOAD_ERR_OK) {
die("File upload failed. Error Code: " . $file["error"]);
}
// Check File Size (2 MB)
$maxSize = 2 * 1024 * 1024;
if ($file["size"] > $maxSize) {
die("Image size must be less than 2 MB.");
}
// Check File Extension
$extension = strtolower(
pathinfo($file["name"], PATHINFO_EXTENSION)
);
$allowedExtensions = ["jpg", "jpeg", "png"];
if (!in_array($extension, $allowedExtensions, true)) {
die("Only JPG, JPEG and PNG images are allowed.");
}
// Check Actual Image Type
$imageInfo = getimagesize($file["tmp_name"]);
if ($imageInfo === false) {
die("Invalid image file.");
}
$allowedMimeTypes = [
"image/jpeg",
"image/png"
];
if (!in_array($imageInfo["mime"], $allowedMimeTypes, true)) {
die("Invalid image format.");
}
// Create Upload Directory
$uploadDirectory = __DIR__ . "/uploads/";
if (!is_dir($uploadDirectory)) {
if (!mkdir($uploadDirectory, 0755, true)) {
die("Unable to create upload directory.");
}
}
// Generate Unique File Name
$newFileName = bin2hex(random_bytes(16)) . "." . $extension;
$destination = $uploadDirectory . $newFileName;
// Move Uploaded File
if (move_uploaded_file($file["tmp_name"], $destination)) {
echo "Image uploaded successfully.";
echo "<br>";
echo "Saved File Name: " . htmlspecialchars($newFileName);
} else {
echo "Unable to upload image.";
}
}
?>Explanation:
Checks whether a file was submitted successfully.
Restricts the maximum file size to 2 MB.
Allows only JPG, JPEG, and PNG extensions.
Uses
getimagesize()to check the actual image format.Creates the
uploadsdirectory if it does not exist.Generates a unique filename using
random_bytes().Uses
move_uploaded_file()to save the image.
Security note: This example is a useful starting point, not a complete production upload system. Store uploads outside the public web root where possible, disable script execution in upload directories, enforce request limits, and apply access controls. Consider decoding and re-encoding images to remove potentially dangerous embedded content.
10. Display an Uploaded Image in PHP
After uploading an image, you can display it on a webpage using the HTML img element.
Example:
<?php
$image = "uploads/profile.jpg";
if (file_exists($image)) {
echo "<img src='" . htmlspecialchars($image) .
"' width='200' alt='Uploaded Image'>";
} else {
echo "Image not found.";
}
?>Output:
The uploaded image will be displayed on the webpage.
The image above is only an illustrative example. Your PHP application displays the actual uploaded image.
11. PHP Upload Error Codes
PHP provides predefined error codes through $_FILES["file"]["error"].
Error Code | Constant | Description |
|---|---|---|
0 |
| File uploaded successfully |
1 |
| File exceeds |
2 |
| File exceeds the form's |
3 |
| File was uploaded partially |
4 |
| No file was uploaded |
6 |
| Temporary folder is missing |
7 |
| Failed to write file to disk |
8 |
| A PHP extension stopped the upload |
You can use these error codes to display meaningful messages to users.
12. PHP Configuration for File Upload
PHP provides configuration settings that control file uploads.
You can check or update these settings in your php.ini file.
Setting | Description | Example |
|---|---|---|
| Enables or disables file uploads |
|
| Maximum size of an individual uploaded file |
|
| Maximum size of the entire POST request |
|
| Maximum number of files uploaded in one request |
|
| Temporary directory for uploaded files | Server-specific path |
Example php.ini Settings:
file_uploads = On
upload_max_filesize = 2M
post_max_size = 8M
max_file_uploads = 20Important: post_max_size should be larger than upload_max_filesize to allow for the complete request, including form data.
After changing php.ini in XAMPP, restart Apache for the changes to take effect.
13. Multiple File Upload in PHP
PHP also supports uploading multiple files using a single HTML form.
To upload multiple files, use the multiple attribute in the file input field and add square brackets to its name.
HTML Form:
<!DOCTYPE html>
<html>
<head>
<title>Multiple File Upload</title>
</head>
<body>
<h2>Upload Multiple Files</h2>
<form method="POST"
action="multiple_upload.php"
enctype="multipart/form-data">
Select Files:
<input type="file"
name="myfiles[]"
multiple
required>
<br><br>
<input type="submit" value="Upload Files">
</form>
</body>
</html>PHP Code: multiple_upload.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach ($_FILES["myfiles"]["name"] as $key => $name) {
if ($_FILES["myfiles"]["error"][$key] === UPLOAD_ERR_OK) {
$tmpName = $_FILES["myfiles"]["tmp_name"][$key];
$destination = "uploads/" . basename($name);
if (move_uploaded_file($tmpName, $destination)) {
echo htmlspecialchars($name) . " uploaded successfully.";
echo "<br>";
} else {
echo "Unable to upload " . htmlspecialchars($name);
echo "<br>";
}
}
}
}
?>Note: This is a basic demonstration. For real applications, validate every file independently and generate unique filenames instead of trusting the original names.
14. Important PHP File Upload Functions
Function | Description |
|---|---|
| Accesses uploaded file information |
| Moves an uploaded file |
| Checks whether a file was uploaded through HTTP POST |
| Gets information about a file path |
| Returns file size |
| Checks whether a file or directory exists |
| Gets image information |
| Creates a directory |
| Generates cryptographically secure random bytes |
| Checks whether a value exists in an array |
| Converts a string to lowercase |
15. Important Points to Remember
Use
method="POST"for file uploads.Always set
enctype="multipart/form-data"in the HTML form.Use
$_FILESto access uploaded file information.Use
move_uploaded_file()to save uploaded files.Validate file size before moving the file.
Check file extensions and actual file content.
Do not trust the original filename or browser-provided MIME type.
Generate unique filenames to avoid overwriting existing files.
Configure
upload_max_filesizeandpost_max_sizeinphp.ini.Never allow users to upload executable PHP files into a publicly accessible upload directory.
Use proper permissions and access controls for uploaded files.
Conclusion
PHP File Upload functionality allows developers to upload images, documents, PDFs, and other files from a user's computer to a web server.
By using $_FILES, move_uploaded_file(), getimagesize(), and other PHP functions, you can build file upload systems with validation and error handling.
These concepts are useful when developing student management systems, employee management applications, profile management systems, document management systems, and dynamic websites.
PHP Sessions and Cookies – How to Create, Store, Access and Destroy Sessions and Cookies in PHP
Sessions and cookies are used in PHP to store information about users while they browse a website. They help websites remember users, maintain login status, store preferences, and manage shopping carts.
In this tutorial, we will learn how to create, access, update, and destroy sessions and cookies in PHP with practical examples.
1. What Are Sessions in PHP?
A session is a way to store user information on the server so that it can be accessed across multiple pages of a website.
For example:
Remembering a logged-in user's information.
Maintaining a user's login status.
Storing shopping cart items.
Managing user permissions.
Temporarily storing form data.
PHP stores session information on the server and uses a session ID to identify each user's session.
Session Syntax
<?php
session_start();
$_SESSION['username'] = 'Rehan';
$_SESSION['email'] = 'rehan@example.com';
echo $_SESSION['username'];
?>Output:
RehanImportant: Always call session_start() before sending any HTML, text, or other output to the browser.
2. How to Create a Session in PHP
To create a session, use the session_start() function and store values inside the $_SESSION superglobal array.
Example:
<?php
session_start();
$_SESSION['name'] = 'Rehan Khan';
$_SESSION['age'] = 25;
$_SESSION['city'] = 'Delhi';
echo "Session Created Successfully!";
?>Output:
Session Created Successfully!Here:
session_start()starts a new session or resumes an existing one.$_SESSION['name']stores the user's name.$_SESSION['age']stores the user's age.$_SESSION['city']stores the user's city.
3. How to Access Session Variables in PHP
You can access session variables from different PHP pages after starting the session.
Example:
Create a file named set_session.php.
<?php
session_start();
$_SESSION['username'] = 'Rehan';
$_SESSION['email'] = 'rehan@example.com';
echo "Session Variables Created Successfully!";
?>Now create another file named get_session.php.
<?php
session_start();
echo "Username: " . $_SESSION['username'] . "<br>";
echo "Email: " . $_SESSION['email'];
?>Output:
Username: Rehan
Email: rehan@example.comBoth files must run through the same website session so PHP can identify the same user.
4. How to Check Whether a Session Variable Exists
Use the isset() function to check whether a session variable has been created.
Example:
<?php
session_start();
$_SESSION['username'] = 'Rehan';
if (isset($_SESSION['username'])) {
echo "Session Variable Exists!";
} else {
echo "Session Variable Does Not Exist!";
}
?>Output:
Session Variable Exists!5. How to Update a Session Variable
You can update a session variable by assigning it a new value.
Example:
<?php
session_start();
$_SESSION['username'] = 'Rehan';
echo "Old Name: " . $_SESSION['username'] . "<br>";
$_SESSION['username'] = 'Rehan Khan';
echo "Updated Name: " . $_SESSION['username'];
?>Output:
Old Name: Rehan
Updated Name: Rehan Khan6. How to Remove a Session Variable
Use the unset() function to remove a specific session variable.
Example:
<?php
session_start();
$_SESSION['username'] = 'Rehan';
$_SESSION['email'] = 'rehan@example.com';
unset($_SESSION['email']);
echo "Username: " . $_SESSION['username'] . "<br>";
if (isset($_SESSION['email'])) {
echo "Email Exists";
} else {
echo "Email Session Removed";
}
?>Output:
Username: Rehan
Email Session Removed7. How to Destroy a Session in PHP
PHP provides two commonly used functions for clearing session data:
session_unset()– Removes all session variables.session_destroy()– Destroys the current session data stored on the server.
Example:
<?php
session_start();
$_SESSION['username'] = 'Rehan';
$_SESSION['email'] = 'rehan@example.com';
// Remove all session variables
session_unset();
// Destroy the session
session_destroy();
echo "Session Destroyed Successfully!";
?>Output:
Session Destroyed Successfully!Note: session_destroy() does not automatically remove the session cookie from the browser. For a complete logout, you should also clear the session cookie.
8. Practical Example: PHP Login Using Sessions
Sessions are commonly used to maintain the login status of users.
In this example, we will create a simple login system using PHP sessions.
Step 1: Create login.php
<?php
session_start();
$error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
// Demo credentials only
if ($username == "admin" && $password == "12345") {
session_regenerate_id(true);
$_SESSION['username'] = $username;
header("Location: dashboard.php");
exit();
} else {
$error = "Invalid Username or Password!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Login System</title>
</head>
<body>
<h2>Login Form</h2>
<form method="POST">
Username:
<input type="text" name="username" required>
<br><br>
Password:
<input type="password" name="password" required>
<br><br>
<button type="submit">Login</button>
</form>
<p><?php echo htmlspecialchars($error); ?></p>
</body>
</html>Step 2: Create dashboard.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: login.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h2>Welcome to Dashboard</h2>
<p>
Welcome,
<?php echo htmlspecialchars($_SESSION['username']); ?>
</p>
<a href="logout.php">Logout</a>
</body>
</html>Step 3: Create logout.php
<?php
session_start();
// Clear all session variables
$_SESSION = [];
// Remove the session cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', [
'expires' => time() - 3600,
'path' => $params['path'],
'domain' => $params['domain'],
'secure' => $params['secure'],
'httponly' => $params['httponly'],
'samesite' => $params['samesite']
]);
}
// Destroy the session
session_destroy();
header("Location: login.php");
exit();
?>How It Works:
The user enters a username and password.
PHP checks the demo credentials.
If the credentials match, PHP creates a session.
The user is redirected to the dashboard.
The dashboard checks whether the session exists.
If the session does not exist, the user is redirected to the login page.
When the user clicks Logout, the session data and session cookie are cleared.
Important: The username and password in this example are only for demonstration. In a real application, validate users against a database and use password_hash() and password_verify() for password storage and verification.
9. What Are Cookies in PHP?
A cookie is a small piece of data stored in the user's web browser.
Cookies help websites remember information about users even after they close and reopen their browser, depending on the cookie's expiration settings.
For example:
Remembering a user's name.
Storing language preferences.
Saving website theme preferences.
Remembering shopping cart preferences.
Maintaining certain user settings.
Unlike sessions, cookies are stored on the client side (in the browser).
10. How to Create a Cookie in PHP
PHP provides the setcookie() function to create cookies.
Cookie Syntax
setcookie(name, value, expires, path, domain, secure, httponly);Example:
<?php
setcookie("username", "Rehan", time() + 3600, "/");
echo "Cookie Created Successfully!";
?>Output:
Cookie Created Successfully!Here:
usernameis the cookie name.Rehanis the cookie value.time() + 3600sets the cookie expiration to one hour from now./makes the cookie available throughout the website.
Important: Call setcookie() before sending any output to the browser. The cookie will normally be available to PHP through $_COOKIE on the next request.
11. How to Access a Cookie in PHP
Use the $_COOKIE superglobal array to access cookie values.
Example:
Create a file named set_cookie.php.
<?php
setcookie("username", "Rehan", time() + 3600, "/");
echo "Cookie Created Successfully!";
?>Now create another file named get_cookie.php.
<?php
if (isset($_COOKIE['username'])) {
echo "Username: " . htmlspecialchars($_COOKIE['username']);
} else {
echo "Cookie Not Found!";
}
?>Output:
Username: RehanOpen get_cookie.php after requesting set_cookie.php so the browser can send the newly created cookie.
12. How to Update a Cookie in PHP
To update a cookie, call setcookie() again using the same cookie name with a new value.
Example:
<?php
setcookie("username", "Rehan Khan", time() + 3600, "/");
echo "Cookie Updated Successfully!";
?>On the next request, the browser will send the updated cookie value.
13. How to Check Whether a Cookie Exists
Use the isset() function to check whether a cookie exists.
Example:
<?php
if (isset($_COOKIE['username'])) {
echo "Cookie Exists!";
} else {
echo "Cookie Does Not Exist!";
}
?>14. How to Delete a Cookie in PHP
To delete a cookie, set its expiration time to a past date.
Example:
<?php
setcookie("username", "", [
'expires' => time() - 3600,
'path' => '/'
]);
echo "Cookie Deleted Successfully!";
?>Output:
Cookie Deleted Successfully!The cookie will be removed by the browser when it processes the expired cookie. Use the same path and domain settings that were used when creating it.
15. How to Set Cookie Expiration Time
You can control how long a cookie remains valid using the time() function.
Example:
<?php
// Cookie expires after 1 hour
setcookie("cookie1", "One Hour", time() + 3600, "/");
// Cookie expires after 1 day
setcookie("cookie2", "One Day", time() + 86400, "/");
// Cookie expires after 7 days
setcookie("cookie3", "Seven Days", time() + (7 * 86400), "/");
echo "Cookies Created Successfully!";
?>Common Expiration Values:
Duration | Seconds |
|---|---|
1 Minute | 60 |
1 Hour | 3600 |
1 Day | 86400 |
7 Days | 604800 |
30 Days | 2592000 |
16. Secure Cookie Settings in PHP
When creating cookies for real websites, you should use security options.
Example:
<?php
setcookie("username", "Rehan", [
'expires' => time() + 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
echo "Secure Cookie Created Successfully!";
?>Explanation:
secure: Sends the cookie only over HTTPS connections.httponly: Prevents JavaScript from accessing the cookie.samesite: Helps protect against certain cross-site request forgery (CSRF) attacks.
For production websites, configure cookie options according to your application's security requirements. Never store passwords or sensitive secrets directly in cookies.
17. Difference Between Sessions and Cookies in PHP
Sessions and cookies both store information, but they work differently.
Sessions | Cookies |
|---|---|
Stored on the server. | Stored in the user's browser. |
Identified using a session ID. | Identified using a cookie name. |
Generally removed when the session expires or is destroyed. | Can remain until their expiration time. |
Can store arrays and other PHP values. | Store string values. |
More suitable for login state and sensitive server-side data. | Suitable for non-sensitive preferences. |
Uses | Uses |
Created using | Created using |
18. Difference Between session_unset() and session_destroy()
session_unset() | session_destroy() |
|---|---|
Removes all session variables. | Destroys session data on the server. |
Does not destroy the session itself. | Destroys the current session. |
Session can continue to be used. | A new session can be started later. |
Does not remove the session cookie. | Does not automatically remove the session cookie. |
19. Important PHP Session and Cookie Functions
Function | Description |
|---|---|
| Starts or resumes a session. |
| Gets or sets the session ID. |
| Removes all session variables. |
| Destroys the current session data. |
| Generates a new session ID. |
| Creates or updates a cookie. |
| Creates a cookie without URL encoding its value. |
| Checks whether a session variable or cookie exists. |
| Removes a specific session variable. |
| Returns the current Unix timestamp. |
20. Conclusion
In this tutorial, we learned about PHP Sessions and Cookies and how to use them in web applications.
We covered:
What sessions and cookies are.
How to create and access sessions.
How to update and remove session variables.
How to destroy a session.
How to create, access, update, and delete cookies.
How to set cookie expiration times.
How to create a practical login system using sessions.
Differences between sessions and cookies.
Sessions are commonly used for login authentication and maintaining user information, while cookies are useful for remembering user preferences and other non-sensitive information.
PHP Error Handling – How to Handle Errors Using try, catch, throw, finally and Custom Exceptions in PHP
Error handling is an important concept in PHP programming. It helps developers identify, manage, and fix errors that occur while executing a PHP application.
For example, errors may occur when:
A user enters invalid data.
A file does not exist.
A database connection fails.
A required variable is missing.
An application encounters an unexpected situation.
PHP provides different methods for handling errors, including error_reporting(), set_error_handler(), try, catch, throw, finally, and custom exceptions.
In this tutorial, we will learn PHP error handling step by step with practical examples.
1. What Is Error Handling in PHP?
Error handling is the process of detecting and managing errors that occur during program execution.
Instead of allowing an application to stop unexpectedly, developers can handle errors and display meaningful messages.
Example:
<?php
echo "Welcome to PHP!";
echo $username;
echo "Program Completed!";
?>In this example, $username has not been declared. PHP may generate a warning about an undefined variable, but execution continues.
Error handling helps developers identify such problems and manage them properly.
2. Types of Errors in PHP
PHP has several types of errors.
1. Parse Error
A parse error occurs when PHP code contains incorrect syntax.
Example:
<?php
echo "Hello World"
?>Error:
Parse error: syntax error, unexpected end of fileIn this example, the semicolon is missing after the echo statement.
2. Fatal Error
A fatal error occurs when PHP encounters a problem that prevents the script from continuing.
Example:
<?php
function displayMessage() {
echo "Hello PHP!";
}
displayMessage();
undefinedFunction();
echo "Program Completed!";
?>Error:
Fatal error: Uncaught Error: Call to undefined function undefinedFunction()The program stops when it tries to call the undefined function.
3. Warning
A warning occurs when PHP encounters a problem but can continue executing the script.
Example:
<?php
include("not_found.php");
echo "Program Completed!";
?>Possible Output:
Warning: include(not_found.php): Failed to open stream
Program Completed!The exact warning message depends on the PHP version and configuration.
4. Notice
A notice indicates a minor issue in the code, such as accessing an undefined variable.
Example:
<?php
echo $username;
echo "Program Completed!";
?>PHP may display an undefined variable warning depending on the PHP version and error reporting configuration.
5. Deprecated Warning
A deprecated warning indicates that a feature or function is outdated and may be removed in a future PHP version.
Example:
<?php
$number = 10;
$number = $number + 5;
echo $number;
?>This example does not generate a deprecated warning. Deprecated warnings occur when using features specifically marked as deprecated by PHP.
3. PHP Error Reporting Using error_reporting()
PHP provides the error_reporting() function to control which errors PHP reports.
Syntax:
error_reporting(level);Example:
<?php
error_reporting(E_ALL);
$username = "Rehan";
echo $username;
?>Output:
RehanHere, E_ALL enables reporting of all error levels supported by the PHP version.
Common Error Reporting Constants
Constant | Description |
|---|---|
| Reports fatal runtime errors. |
| Reports runtime warnings. |
| Reports syntax parsing errors. |
| Reports notices. |
| Reports deprecated features. |
| User-generated fatal error. |
| User-generated warning. |
| User-generated notice. |
| Reports all supported error levels. |
Example: Reporting All Errors
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$username = "Rehan";
echo $username;
?>Important: Displaying errors is useful during development. On a production website, disable displaying errors to visitors and log errors instead.
4. How to Display PHP Errors Using ini_set()
The ini_set() function changes PHP configuration settings during script execution.
Example:
<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);
echo $username;
?>This enables error display and reporting for the current script, subject to server configuration and PHP error handling.
5. PHP Error Handling Using set_error_handler()
PHP provides the set_error_handler() function to create a custom error handler.
It allows developers to define what should happen when certain PHP errors occur.
Syntax:
set_error_handler(callback);Example:
<?php
function customErrorHandler($errno, $errstr, $errfile, $errline) {
echo "Error Number: " . $errno . "<br>";
echo "Error Message: " . $errstr . "<br>";
echo "Error File: " . $errfile . "<br>";
echo "Error Line: " . $errline;
}
set_error_handler("customErrorHandler");
echo $username;
?>Possible Output:
Error Number: 2
Error Message: Undefined variable $username
Error File: /path/to/file.php
Error Line: 15The actual file path and line number depend on your PHP file.
Explanation:
$errnocontains the error level.$errstrcontains the error message.$errfilecontains the file name.$errlinecontains the line number.
Note: A custom error handler generally handles PHP errors such as warnings and notices. It does not handle every error type, including parse errors and all fatal errors.
6. PHP Error Handling Using trigger_error()
The trigger_error() function allows developers to generate their own PHP errors.
Syntax:
trigger_error("Error Message", E_USER_WARNING);Example:
<?php
$age = 15;
if ($age < 18) {
trigger_error("You are not eligible to register!", E_USER_WARNING);
}
echo "Program Completed!";
?>Possible Output:
Warning: You are not eligible to register!
Program Completed!You can use the following error levels:
E_USER_ERRORE_USER_WARNINGE_USER_NOTICEE_USER_DEPRECATED
These are user-generated errors that can also be handled by a custom error handler.
7. What Is Exception Handling in PHP?
An exception is an object that represents an unexpected or exceptional situation during program execution.
PHP provides exception handling using four important keywords:
trycatchthrowfinally
Exception handling helps developers manage problems without immediately terminating the entire application.
8. PHP try and catch
The try block contains code that may generate an exception.
The catch block handles the exception if one is thrown.
Syntax:
try {
// Code that may generate an exception
} catch (Exception $e) {
// Handle the exception
}Example:
<?php
try {
$number = 10;
if ($number < 20) {
throw new Exception("Number must be greater than or equal to 20!");
}
echo "Valid Number!";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>Output:
Error: Number must be greater than or equal to 20!Explanation:
The
tryblock executes the code.The
throwkeyword generates an exception.The
catchblock catches the exception.getMessage()returns the exception message.
9. PHP throw Keyword
The throw keyword is used to generate an exception manually.
Example:
<?php
$age = 16;
if ($age < 18) {
throw new Exception("You are not eligible to vote!");
}
echo "You are eligible to vote!";
?>This example throws an exception when the age is below 18.
If no matching exception handler catches it, PHP reports an uncaught exception and terminates the script.
Better Approach Using try and catch:
<?php
try {
$age = 16;
if ($age < 18) {
throw new Exception("You are not eligible to vote!");
}
echo "You are eligible to vote!";
} catch (Exception $e) {
echo $e->getMessage();
}
?>Output:
You are not eligible to vote!10. PHP finally Keyword
The finally block contains code that executes after the try and catch blocks, whether an exception occurs or not, in normal exception handling flow.
It is commonly used for cleanup operations.
Example:
<?php
try {
echo "Try Block Executed!<br>";
throw new Exception("Something went wrong!");
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "<br>";
} finally {
echo "Finally Block Executed!";
}
?>Output:
Try Block Executed!
Error: Something went wrong!
Finally Block Executed!Example Without Exception:
<?php
try {
echo "Try Block Executed!<br>";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "<br>";
} finally {
echo "Finally Block Executed!";
}
?>Output:
Try Block Executed!
Finally Block Executed!11. Multiple catch Blocks in PHP
You can use multiple catch blocks to handle different types of exceptions.
Example:
<?php
try {
$number = 0;
if ($number == 0) {
throw new InvalidArgumentException("Number cannot be zero!");
}
echo 100 / $number;
} catch (InvalidArgumentException $e) {
echo "Invalid Argument: " . $e->getMessage();
} catch (Exception $e) {
echo "General Error: " . $e->getMessage();
}
?>Output:
Invalid Argument: Number cannot be zero!The more specific exception should be caught before a more general parent exception.
12. PHP Exception Class and Common Methods
PHP provides a built-in Exception class.
You can use its methods to get information about an exception.
Common Exception Methods:
Method | Description |
|---|---|
| Returns the exception message. |
| Returns the exception code. |
| Returns the file where the exception occurred. |
| Returns the line number. |
| Returns the stack trace as an array. |
| Returns the stack trace as a string. |
Example:
<?php
try {
throw new Exception("Database Connection Failed!", 101);
} catch (Exception $e) {
echo "Message: " . $e->getMessage() . "<br>";
echo "Code: " . $e->getCode() . "<br>";
echo "File: " . $e->getFile() . "<br>";
echo "Line: " . $e->getLine();
}
?>Possible Output:
Message: Database Connection Failed!
Code: 101
File: /path/to/file.php
Line: 5The file path and line number depend on where you execute the code.
13. PHP Custom Exceptions
A custom exception is an exception class created by the developer to handle specific application errors.
You can create a custom exception by extending PHP's built-in Exception class.
Example:
<?php
class AgeException extends Exception {
public function displayError() {
return "Age Error: " . $this->getMessage();
}
}
try {
$age = 15;
if ($age < 18) {
throw new AgeException("Age must be 18 or above!");
}
echo "Registration Successful!";
} catch (AgeException $e) {
echo $e->displayError();
}
?>Output:
Age Error: Age must be 18 or above!Here, AgeException is a custom exception class created by extending the built-in Exception class.
14. PHP Error Logging Using error_log()
The error_log() function is used to send error messages to the configured PHP error log or another supported destination.
It is useful when you do not want to display technical errors to website visitors.
Example:
<?php
$errorMessage = "Database Connection Failed!";
error_log($errorMessage);
echo "Something went wrong. Please try again later.";
?>Browser Output:
Something went wrong. Please try again later.The technical error message is sent to the configured PHP error log.
You can also write a message to a specific log file:
<?php
$errorMessage = "Unable to connect to database!";
error_log($errorMessage . PHP_EOL, 3, "errors.log");
echo "Error Logged Successfully!";
?>This example writes the message to errors.log in the current working directory, provided PHP has permission to write there.
15. Practical Example: PHP Division Calculator With Exception Handling
Let's create a simple calculator that divides two numbers and handles division by zero.
Example:
<?php
$result = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
try {
$num1 = filter_input(INPUT_POST, "num1", FILTER_VALIDATE_FLOAT);
$num2 = filter_input(INPUT_POST, "num2", FILTER_VALIDATE_FLOAT);
if ($num1 === false || $num1 === null ||
$num2 === false || $num2 === null) {
throw new InvalidArgumentException("Please enter valid numbers!");
}
if ($num2 == 0) {
throw new DivisionByZeroError("Cannot divide by zero!");
}
$result = "Result: " . ($num1 / $num2);
} catch (InvalidArgumentException $e) {
$result = "Error: " . $e->getMessage();
} catch (DivisionByZeroError $e) {
$result = "Error: " . $e->getMessage();
} finally {
// Cleanup code can be written here.
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Calculator</title>
</head>
<body>
<h2>Division Calculator</h2>
<form method="POST">
Enter First Number:
<input type="number" step="any" name="num1" required>
<br><br>
Enter Second Number:
<input type="number" step="any" name="num2" required>
<br><br>
<button type="submit">Calculate</button>
</form>
<h3>
<?php echo htmlspecialchars($result); ?>
</h3>
</body>
</html>Example Output 1:
If the user enters:
First Number: 100
Second Number: 10Result:
Result: 10Example Output 2:
If the user enters:
First Number: 100
Second Number: 0Result:
Error: Cannot divide by zero!Explanation:
The user enters two numbers.
PHP validates the submitted values.
The
tryblock performs the division.If the second number is zero, PHP throws a
DivisionByZeroError.The appropriate
catchblock handles the error.The result or error message is displayed on the webpage.
16. Difference Between Errors and Exceptions in PHP
Errors | Exceptions |
|---|---|
Represent problems that occur during PHP execution. | Represent exceptional situations handled through exception objects. |
Can be reported or handled using error handlers. | Handled using |
Examples include warnings and parse errors. | Examples include |
Some errors stop script execution. | An uncaught exception stops normal execution. |
Can be generated by PHP or using error-triggering functions. | Can be generated using the |
Important: PHP 7 and later also use the Throwable interface. Both Exception and PHP engine errors such as TypeError and DivisionByZeroError implement Throwable.
If you want to catch both exceptions and engine errors, you can use:
<?php
try {
// Code that may throw an exception or error
} catch (Throwable $e) {
echo "Error: " . $e->getMessage();
}
?>17. Important PHP Error Handling Functions and Keywords
Function / Keyword | Description |
|---|---|
| Controls which errors are reported. |
| Changes PHP configuration settings. |
| Sets a custom error handler. |
| Restores the previous error handler. |
| Generates a user-level error. |
| Sends an error message to a log. |
| Defines code that may generate an exception. |
| Handles an exception or error. |
| Throws an exception or error object. |
| Executes cleanup code after exception handling. |
| Returns the exception message. |
18. Best Practices for PHP Error Handling
Follow these best practices when developing PHP applications:
Always enable
E_ALLduring development.Use
tryandcatchfor operations that may throw exceptions.Use custom exceptions when your application needs specific error handling.
Log technical errors instead of displaying them to website visitors.
Never expose database passwords or sensitive information in error messages.
Validate user input before processing it.
Use meaningful error messages.
Use
finallyfor cleanup operations when necessary.Avoid ignoring errors without understanding their cause.
Configure production applications to hide detailed error messages from visitors.
19. Conclusion
In this tutorial, we learned about PHP Error Handling and how to manage different types of errors in PHP applications.
We covered:
What error handling is.
Types of PHP errors.
PHP error reporting using
error_reporting().Displaying errors using
ini_set().Custom error handling using
set_error_handler().Generating errors using
trigger_error().Exception handling using
try,catch,throw, andfinally.Multiple catch blocks.
Built-in exception methods.
Custom exception classes.
Error logging using
error_log().A practical division calculator using exception handling.
Error handling makes PHP applications more reliable, secure, and easier to debug.
Comments
Post a Comment