what is oops concept in php
Object-Oriented Programming (OOP) in PHP is a programming paradigm that organizes code
into reusable, modular components called "objects". This approach structures code around
the concepts of classes and objects, emphasizing four core principles: encapsulation,
inheritance, polymorphism, and abstraction.
Core OOP concepts in PHP
Classes and objects
Class: A class serves as a blueprint for creating objects, defining properties (data) and
methods (behavior).
Object: An object is an instance of a class, inheriting its structure but holding unique data
values.
The four pillars of OOP
1. Encapsulation: Access and data integrity
Encapsulation bundles properties and methods within a class, controlling access to internal
data. This prevents unwanted interference and misuse, enhancing data integrity.
Access modifiers:
public: Default access. Properties and methods are accessible from anywhere, both inside
and outside the class.
protected: Properties and methods are only accessible within the class itself and by its
inheriting (child) classes.
private: Restricts access to the class where the property or method is defined. Child classes
cannot access private members.
Getters and setters: To interact with private or protected properties, you must create public
methods known as "getters" (accessors) and "setters" (mutators). This provides a controlled
interface for data manipulation.
php
<?php
class User {
private string $email;
public function setEmail(string $email): void {
// Add validation logic here
$this->email = $email;
}
public function getEmail(): string {
return $this->email;
$user = new User();
$user->setEmail("name@[Link]");
echo $user->getEmail(); // Outputs: name@[Link]
// Attempting to access $user->email would cause an error
?>
Use code with caution.
2. Inheritance: Code reuse and hierarchy
Inheritance allows you to create a hierarchy of related classes that share common
functionality, promoting the "Don't Repeat Yourself" (DRY) principle. A child class uses
the extends keyword to inherit non-private properties and methods from a parent class.
Method overriding: A child class can provide a new implementation for a method that is
already defined in its parent class. The appropriate method is then called at runtime,
depending on the object's type.
php
<?php
class Animal {
public function makeSound(): void {
echo "The animal makes a sound.\n";
class Dog extends Animal {
// Overrides the parent method
public function makeSound(): void {
echo "Woof! Woof!\n";
}
$animal = new Animal();
$dog = new Dog();
$animal->makeSound(); // Outputs: The animal makes a sound.
$dog->makeSound(); // Outputs: Woof! Woof!
?>
Use code with caution.
3. Polymorphism: Flexible and interchangeable objects
Polymorphism, meaning "many forms," allows objects of different classes that implement
the same interface or extend the same base class to be treated as a common type. This
promotes flexibility and adaptability in your code.
Polymorphism with interfaces:
A common interface defines a contract for behavior. Any class that implements this interface
can be used interchangeably, as shown in this example:
php
<?php
interface Shape {
public function getArea(): float;
class Circle implements Shape {
public float $radius;
public function __construct(float $radius) {
$this->radius = $radius;
public function getArea(): float {
return pi() * ($this->radius ** 2);
class Square implements Shape {
public float $side;
public function __construct(float $side) {
$this->side = $side;
public function getArea(): float {
return $this->side ** 2;
function printArea(Shape $shape): void {
echo "Area: " . $shape->getArea() . "\n";
$circle = new Circle(5);
$square = new Square(4);
printArea($circle); // Outputs: Area: 78.5398...
printArea($square); // Outputs: Area: 16
?>
Use code with caution.
4. Abstraction: Simplification through selective detail
Abstraction hides complex implementation details and shows only the essential features of
an object. In PHP, this is achieved using abstract classes and interfaces.
Abstract classes:
Cannot be instantiated on their own; they must be extended by a child class.
Can contain both regular methods (with implementation) and abstract methods (without
implementation).
Abstract methods must be implemented by any child class.
Interfaces:
Define a contract that a class must follow, specifying methods that must be implemented.
Unlike abstract classes, they contain no method bodies and cannot have properties.
A class can implement multiple interfaces, but only extend one abstract class.
Other advanced OOP features in PHP
Traits
Used for code reuse in single-inheritance languages like PHP.
Allow you to reuse sets of methods in different, independent classes.
Help reduce code duplication without the strict hierarchy of inheritance.
Namespaces
Used to group related classes, interfaces, and functions, which helps avoid name collisions in
larger applications.
Essential for organizing complex codebases and integrating third-party libraries.
Work with PHP's autoloader to automatically load class files when needed.
Final keyword
Can be used on a class to prevent it from being extended.
Can be used on a method to prevent it from being overridden by child classes.
Used to enforce a specific behavior that should not be changed.
Magic methods
Special methods in PHP that start with a double underscore
(e.g., __construct(), __get(), __set()).
__construct() is a constructor called automatically when a new object is created.
__destruct() is called when an object is no longer needed.
__get() and __set() are used to handle access to properties that do not exist or are not
visible.
what is PHP form
A PHP form is not a specific type of form but rather
an HTML form whose data is processed by a PHP script on a web server. The HTML form is the user-
facing part, with input fields and a submit button, while the PHP script handles the server-side tasks
like data collection, validation, and storage.
How a PHP form works
The interaction between the user, the HTML form, and the PHP script follows these steps:
1. Form creation: The developer creates an HTML form using the <form> tag, specifying where
the data should be sent (action) and how it should be sent (method).
2. User input: A user fills out the form in their web browser.
3. Form submission: The user clicks a submit button. The browser then sends the form data to
the web server, using the HTTP method defined in the form's method attribute.
4. PHP processing: The web server passes the submitted data to the specified PHP script. PHP
makes this data available through the superglobal variables $_GET or $_POST, depending on
the form's method.
5. Data handling: The PHP script can then validate, sanitize, and process the data. This could
involve saving it to a database, sending an email, or performing other logic.
6. Response: The PHP script generates an HTML response, which is sent back to the user's
browser for display.
what is form handling and validation in php
Form handling
in PHP is the process of collecting, processing, and managing data that users submit through
an HTML form. Form validation is a critical security step within this process that ensures the
submitted data is correct, safe, and adheres to the application's rules.
PHP form handling
PHP, a server-side language, processes the data from an HTML form after a user clicks the
submit button.
Key elements of form handling include:
HTML form setup: A form is defined using the <form> tag in HTML. The action attribute
specifies the PHP script that will process the data, and the method attribute is set
to POST or GET to determine how the data is sent.
Data collection: PHP uses superglobal arrays ($_POST or $_GET) to collect the form data. The
array keys correspond to the name attributes of the form's input fields.
Processing: After collecting the data, the PHP script performs the required business logic,
such as saving data to a database, sending an email, or displaying a personalized response.
Response: Finally, the PHP script generates an HTML response and sends it back to the user's
browser.
PHP form validation
Form validation is a crucial step that checks and cleans user input to prevent security
vulnerabilities and ensure data integrity. Validation should always be performed on the
server-side, even if client-side validation (with JavaScript) is also used, as malicious users can
bypass client-side checks.
Key validation and security techniques
1. Sanitizing input
Sanitization is the process of cleaning user data by removing or modifying potentially
harmful characters.
htmlspecialchars(): Converts special characters (like <, >, &) into HTML entities, which
prevents Cross-Site Scripting (XSS) attacks by neutralizing any injected HTML or JavaScript.
trim(): Removes unnecessary whitespace (spaces, tabs, newlines) from the beginning and
end of a string.
filter_var(): A powerful function for filtering variables. It can be used with flags
like FILTER_SANITIZE_EMAIL or FILTER_SANITIZE_URL to remove illegal characters.
2. Validating input
Validation checks if the user's input meets the application's specific requirements.
Required fields: Use empty() or isset() to check if a mandatory field has been filled in.
Email validation: Check for a correctly formatted email address
using filter_var($_POST["email"], FILTER_VALIDATE_EMAIL).
Numeric validation: Ensure input is a valid number using is_numeric() or filter_var().
Regular expressions: For more complex validation, such as checking phone numbers or
specific formats, preg_match() can be used.
3. Avoiding security vulnerabilities
SQL injection: The most effective way to prevent SQL injection is to use prepared
statements when interacting with a database. This separates the SQL code from the user
data, so malicious commands cannot be executed.
XSS attacks: As mentioned, htmlspecialchars() is essential for preventing XSS by escaping
output.
Protecting $_SERVER["PHP_SELF"]: This variable can be exploited to inject XSS commands.
Always pass it through htmlspecialchars() if you use it in your form's action attribute.
A typical validation pattern in PHP
A robust form processing script often follows a similar pattern:
1. Check if the form has been submitted using $_SERVER["REQUEST_METHOD"] == "POST".
2. Create an empty array for errors and an empty array for sanitized data.
3. For each input field:
1. Validate: Check if the input is present and meets the necessary criteria. If not, add an
error message to the errors array.
2. Sanitize: Clean the input using functions like trim() and htmlspecialchars().
4. After checking all fields, if the error array is empty, the data is safe to process (e.g., store in a
database).
5. If there are errors, reload the form with the user's previous (unprocessed) data and display
the specific error messages to guide the user.
Security and validation
To protect your website from malicious attacks like cross-site scripting (XSS) and SQL injection, PHP
forms require careful validation and sanitation.
Validation: Checks if the user input meets expected requirements (e.g., if a field is not empty,
if an email is in a valid format).
Sanitization: Cleans user input by removing or encoding potentially harmful characters.
The htmlspecialchars() function is often used for this.
Prepared Statements: When interacting with a database, using prepared statements is the
most effective way to prevent SQL injection attacks.
Define get and post methods in php
In PHP, the
GET and POST methods are HTTP request methods used to send form data from a client (a web
browser) to a server. PHP provides built-in superglobal arrays, $_GET and $_POST, to automatically
handle this data on the server side.
The GET method
The GET method appends form data as a query string to the URL. In PHP, this data is automatically
stored in the $_GET superglobal array.
Characteristics:
Data visibility: The data is fully visible in the browser's address bar and is also saved in the
browser's history.
Data size: GET has a character limit, typically around 2048 characters, making it unsuitable
for large amounts of data.
Security: It is less secure because sensitive data, like passwords, is exposed in the URL. For
this reason, you should never use GET for confidential information.
Caching and bookmarks: Since the data is in the URL, GET requests can be easily bookmarked
and cached by the browser, which can improve performance for subsequent requests.
Use case: It is best used for retrieving non-sensitive data, such as search queries, filtering
options, or for requests that do not alter data on the server.
Example:
HTML:
html
<form action="[Link]" method="GET">
Name: <input type="text" name="name">
<input type="submit">
</form>
Use code with caution.
Browser URL after submission: [Link]?name=John
PHP ([Link]):
php
<?php
echo "Welcome " . htmlspecialchars($_GET["name"]);
?>
Use code with caution.
The POST method
The POST method sends form data in the body of the HTTP request, keeping it invisible in the URL. In
PHP, this data is accessed via the $_POST superglobal array.
Characteristics:
Data visibility: The data is hidden from the user in the URL, providing a more secure way to
transmit information.
Data size: There is no restriction on the amount of data that can be sent, making it suitable
for forms with numerous fields or for file uploads.
Security: It is the preferred method for sending sensitive information, like passwords, as the
data is not visible in the URL or stored in the browser's history.
Caching and bookmarks: POST requests cannot be bookmarked and are not cached by the
browser.
Use case: Ideal for submitting data that will create or update resources on the server, such as
user registration, order placement, or uploading files.
Example:
HTML:
html
<form action="[Link]" method="POST">
Name: <input type="text" name="name">
<input type="submit">
</form>
Use code with caution.
PHP ([Link]):
php
<?php
echo "Welcome " . htmlspecialchars($_POST["name"]);
?>
GET vs. POST methods
The method attribute of the HTML <form> tag determines how the data is sent.
POST: Sends data in the body of the HTTP request, making it invisible in the browser's URL
bar. It is ideal for submitting sensitive information, such as passwords, and for sending large
amounts of data. The data is accessed in PHP using the $_POST superglobal.
GET: Appends the form data to the URL as a query string. It is suitable for non-sensitive data,
like search queries, and has a character limit. The data is accessed in PHP using
the $_GET superglobal.
Choosing between GET and POST
Feature GET POST
Data Appended to the URL Contained in the HTTP request body
location
Visibility Visible in the URL and history Hidden from the user in the URL
Data size Limited by URL length (approx. 2048 No size limitations
characters)
Security Less secure; should not be used for More secure; suitable for sensitive data
sensitive data
Use cases Data retrieval, search queries, filtering, Submitting data, creating/updating resources,
and pagination and file uploads
Caching Can be cached by browsers and proxies Not cached by default
Idempotency Idempotent (multiple identical requests Non-idempotent (multiple identical requests can
have the same effect as one) have different side effects)
Introduction to cookies
A cookie is a small text file that a web server embeds on a user's web browser. Cookies allow
websites to store information on the client-side, typically for purposes like personalization, session
management, and tracking user behavior.
Storage of cookies at client side
When a web server sends a cookie to a browser, the browser stores it in a designated location on the
user's device. This can be a specific file or a folder managed by the browser. The storage is client-side,
meaning it is saved on the user's computer, not on the server.
Using information of cookies
Cookies are used to retrieve information that the server previously stored on the user's browser. The
browser sends the cookie back to the web server with each subsequent request, allowing the server
to recognize the user and remember their preferences.
How to use cookies in PHP
1. Setting a cookie: Use the setcookie() function in PHP, which must be called before any HTML
output is sent.
php
<?php
$cookie_name = "user_preference";
$cookie_value = "dark_mode";
$expiration = time() + (86400 * 30); // 30 days
setcookie($cookie_name, $cookie_value, $expiration, "/");
?>
2. Accessing a cookie: Use the $_COOKIE superglobal array to access the value of a cookie.
php
<?php
if (isset($_COOKIE["user_preference"])) {
echo "User prefers: " . $_COOKIE["user_preference"];
?>
3. Deleting a cookie: To delete a cookie, set its expiration date to a time in the past.
php
<?php
setcookie("user_preference", "", time() - 3600);
?>
Creating single or multiple server-side sessions
In PHP, a session is a way to store data on the server-side, which is much more secure than storing it
in client-side cookies.
How sessions work
1. Start a session: Begin every script that uses session variables with
the session_start() function. This must be the very first thing in your PHP script.
2. Session ID: When a session starts, PHP automatically generates a unique session ID. By
default, this ID is stored as a cookie (PHPSESSID) on the user's browser.
3. Data storage: On the server, PHP stores the session data in a temporary file that is named
after the session ID. All session variables are stored in the $_SESSION superglobal array.
Example: Creating a single session
php
<?php
// On page 1 (e.g., [Link])
session_start();
$_SESSION["username"] = "JohnDoe";
echo "Session created with username: " . $_SESSION["username"];
?>
php
<?php
// On page 2 (e.g., [Link])
session_start();
if (isset($_SESSION["username"])) {
echo "Welcome back, " . $_SESSION["username"] . "!";
} else {
echo "Session not found.";
}
?>
Creating multiple sessions
You don't create multiple sessions for a single user, but rather use multiple key-value pairs within the
single $_SESSION array to store different pieces of information. For example, you can store a
username, user ID, and cart items all within one session.
php
<?php
session_start();
$_SESSION["user_id"] = 123;
$_SESSION["cart_items"] = ["item1", "item2"];
$_SESSION["theme"] = "light";
?>
Timeout in sessions
By default, PHP sessions expire when the user closes their browser. For security, it is best practice to
implement an inactivity-based timeout to automatically log users out after a period of inactivity.
How to implement a session timeout
1. Set a maximum lifetime: The session.gc_maxlifetime setting in [Link] controls how long
session data is kept on the server. You can change this setting at runtime using ini_set().
2. Custom inactivity timer: A more robust method is to use a timestamp in the $_SESSION array
to track the last activity time.
1. On every page load: Start the session and check if the elapsed time since the last
activity exceeds the timeout period.
2. If timed out: Destroy the session and redirect the user to the login page.
3. If active: Update the timestamp to the current time.
Example: Custom timeout logic
php
<?php
session_start();
$timeout_duration = 1800; // 30 minutes in seconds
if (isset($_SESSION["LAST_ACTIVITY"]) && (time() - $_SESSION["LAST_ACTIVITY"] >
$timeout_duration)) {
// Last activity was more than 30 minutes ago
session_unset(); // Unset $_SESSION variables
session_destroy(); // Destroy the session data on the server
header("Location: [Link]"); // Redirect to login page
exit();
$_SESSION["LAST_ACTIVITY"] = time(); // Update last activity time on every page load
?>