0% found this document useful (0 votes)
27 views14 pages

Oop (Unit 4)

Uploaded by

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

Oop (Unit 4)

Uploaded by

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

OOP :

In object-oriented programming (OOP), classes and objects are fundamental concepts that

allow you to model and organize your code in a more modular and reusable way. Let‟s break

down these concepts in the context of PHP, using simple language and a real-time example.

Class:

A class is like a blueprint or a template that defines a type of object. It encapsulates the

properties (attributes) and behaviors (methods) that objects of that type will have. In PHP, you

define a class using the class keyword.

<?php
class Dog {

public $name;
public $breed;

public function bark() {


echo "Woof! Woof!";
}

public function fetch() {


echo "{$this->name} is fetching.";
}
}
?>

In this example, we‟ve created a Dog class with properties ($name and $breed) and methods

(bark and fetch).


Object:

An object is an instance of a class. It‟s a concrete realization of the blueprint defined by the

class. You can create multiple objects from the same class, each with its own set of property

values.

<?php
// Creating objects from the Dog class
$dog1 = new Dog();
$dog2 = new Dog();

// Setting property values


$dog1->name = "Buddy";
$dog1->breed = "Labrador";

$dog2->name = "Max";
$dog2->breed = "Golden Retriever";

// Calling methods
$dog1->bark(); // Outputs: Woof! Woof!
$dog2->fetch(); // Outputs: Max is fetching.
?>

In this example, we‟ve created two instances ($dog1 and $dog2) of the Dog class. Each object

has its own set of properties and can invoke the methods defined in the class.

The Four pillars of OOPs are abstraction, encapsulation, inheritance, and polymorphism.

Abstraction:

Abstraction in object-oriented programming (OOP) refers to the concept of hiding the

complex implementation details of an object and exposing only the essential features or

functionalities. It allows you to focus on what an object does rather than how it achieves its

functionality. In PHP, abstraction is achieved through abstract classes and interfaces.


Imagine you‟re building a system to manage different shapes like circles, rectangles, and

triangles. Each shape has an area, but the way you calculate the area for each shape is

different.

Here‟s an example in PHP:

// Abstract class representing a shape


abstract class Shape {
// Abstract method for calculating the area
abstract public function calculateArea();
}

class Circle extends Shape {


private $radius;

public function __construct($radius) {


$this->radius = $radius;
}

public function calculateArea() {


return pi() * pow($this->radius, 2);
}
}

class Rectangle extends Shape {


private $length;
private $width;

public function __construct($length, $width) {


$this->length = $length;
$this->width = $width;
}

public function calculateArea() {


return $this->length * $this->width;
}
}

$circle = new Circle(5);


$rectangle = new Rectangle(4, 6);

echo 'Circle Area: ' . $circle->calculateArea() . PHP_EOL;


echo 'Rectangle Area: ' . $rectangle->calculateArea() . PHP_EOL;
In this example, the Shape class is an abstract class that defines the common behavior for all

shapes, which is the calculation of the area. The Circle and Rectangle classes are concrete

classes that inherit from the Shape class and provide their specific implementations for

calculating the area.

Encapsulation:

Encapsulation is one of the four fundamental principles, along with inheritance,

polymorphism, and abstraction. Encapsulation refers to the bundling of data and the methods

that operate on that data into a single unit, often called a class. The main idea is to hide the

internal details of how an object works and expose only what is necessary for the outside

world to interact with it.

Let‟s use a simple real-time example

class Car {
// Private properties (attributes)
private $model;
private $color;
private $fuelLevel;

public function __construct($model, $color) {


$this->model = $model;
$this->color = $color;
$this->fuelLevel = 100;
}

// Public method to get the model of the car


public function getModel() {
return $this->model;
}

// Public method to get the color of the car


public function getColor() {
return $this->color;
}
// Public method to get the fuel level of the car
public function getFuelLevel() {
return $this->fuelLevel;
}

// Public method to simulate driving, reducing fuel level


public function drive() {
// Simulate driving by reducing fuel level
$this->fuelLevel -= 10;
if ($this->fuelLevel < 0) {
$this->fuelLevel = 0; // Ensure fuel level doesn't go below 0
}
}
}

$myCar = new Car("Toyota", "Blue");

echo "Model: " . $myCar->getModel() . "<br>";


echo "Color: " . $myCar->getColor() . "<br>";
echo "Fuel Level: " . $myCar->getFuelLevel() . "%<br>";

$myCar->drive();

echo "Updated Fuel Level after driving: " . $myCar->getFuelLevel() . "%";

In this example:

 The Car class encapsulates the internal details (model, color, and fuel level) by

declaring them as private properties.

 The internal details are hidden from external code, and access is controlled through

these public methods, providing a level of abstraction.

Inheritance:

Inheritance is a concept where a new class (called the child or subclass) can inherit attributes

and behaviors (properties and methods) from an existing class (called the parent or

superclass). This allows you to create a relationship between classes.


// Parent class
class Animal {
public $name;

public function __construct($name) {


$this->name = $name;
}

public function eat() {


return $this->name . ' is eating.';
}
}

// Child class inheriting from Animal


class Dog extends Animal {
public function bark() {
return $this->name . ' is barking.';
}
}

// Child class inheriting from Animal


class Cat extends Animal {
public function meow() {
return $this->name . ' is meowing.';
}
}

// Create instances of the classes


$dog = new Dog('Buddy');
$cat = new Cat('Whiskers');

// Using inherited methods


echo $dog->eat(); // Output: Buddy is eating.
echo $dog->bark(); // Output: Buddy is barking.

echo $cat->eat(); // Output: Whiskers is eating.


echo $cat->meow(); // Output: Whiskers is meowing.

In this example, we have a parent class Animal with a property $name and a method eat().

The Dog and Cat classes are child classes that inherit from the Animal class. They not only

inherit the property and method from Animal but can also have their own unique methods

(bark() for Dog and meow() for Cat).


By using inheritance, you avoid duplicating common code in each class and promote a more

organized and reusable code structure.

The different types of errors including error logs, error handling, error handling functions,
and other error PHP framework error handling. Let‟s start by defining the difference between
the terms “error” and “exception” and other common terms in PHP.

Errors vs. Exceptions

Many use error handling and exception handling interchangeably. When we say error
handling we are referring to the process of catching errors produced by your program which
needs proper action. Since PHP came into a new object-oriented (OOP) way of dealing with
errors, exception handling was introduced. It is used to change the usual way of handling
code execution of a specific error condition when it occurs. In this way, exception handling
provides a better technique over error handling.

How does exception handling in PHP work?

Just like any other object-oriented programming, PHP also uses the following keywords
related to exceptions:

Try: this means that if the exception does not trigger, the code will just execute normally but
if the exception triggers then it will call “thrown” exception

Throw: every time an exception has been triggered, a “throw” exception must be paired with
at least one “catch”

Catch: this block of code should retrieve an exception and create an object including the
exception information.

Error logs

Error logs are crucial during development because this allows developers to see the errors,
warning, notices, etc. that were logged while the application is running. Most of the time,
when a web application is deployed, all errors and warnings are suppressed to prevent
ordinary users from seeing the errors that will arise. Even though the errors and warnings are
hidden from the regular users, the web server still logs every event the website encounters.

Simple error handling

Whenever the application is in an incorrect state in which it cannot recover, then the program
is in an error state.

// Set MySQLi to throw exceptions


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection2 = mysqli_connect('localhost', 'root1', 'Abc123456!', 'testx');
} catch (mysqli_sql_exception $ex) {
throw new Exception("Can't connect to the database! \n" . $ex);
}

Fatal error: Uncaught Exception: Can't connect to the database! mysqli_sql_exception:


Access denied for user 'root1'@'localhost' to database 'testx'

Because the parameters for the mysqli_connect are incorrect, the best way to handle this kind
of scenario is the program throwing an exception. It‟s pointless that the application continue
executing because it would not still return some data from the database.

Using die() or exit() for handling errors

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection2 = mysqli_connect('localhost', 'root1', 'Abc123456!', 'testx');
} catch (mysqli_sql_exception $ex) {
die("Can't connect to the database! \n" . $ex);
}

Retrace error logging

In Retrace, all errors are recorded together with some important information about that error
like the time it occurred, the method that caused it, and the exception it generated. The
number of times the error occurred in a particular time frame is also graphed. From this data,
developers can easily look at what caused the error and then apply a fix. Project managers
can also prioritize which issue to fix based on the number of occurrence of an error.

PHP error handling functions

function myTestFunctionHello($str)f
{
echo "\nHi: $str";
myTestFunctionGoodbye($str);
}

function myTestFunctionGoodbye($str)
{
echo "\nGoodbye: $str";
print_r(debug_backtrace());
}

myTestFunctionHello('World');

// output
{[0]=> array(4) { ["file"]=> string(43) "\var\www\test-error.php" ["line"]=> int(6)
["function"]=> string(21) "myTestFunctionGoodbye" ["args"]=> array(1)
{ [0]=> string(5) "World" }
}
[1]=> array(4){ ["file"]=> string(43) "\var\www\test-error.php" ["line"]=> int(15)
["function"]=> string(19) "myTestFunctionHello" ["args"]=> array(1)
{ [0]=> string(5) "World" }
}}

The debug_backtrace allows developers to see which function was called first. Essentially,
this will return an array of function calls, lines, objects, class, etc. This is helpful in tracing
errors because any fix made can affect the other functions that calls or use it. A similar
function, debug_print_backtrace, also gives similar output but with more details.

echo $unknown_a;
echo $unknown_b;
print_r(error_get_last());
Array ( [type] => 8 [message] => Undefined variable: unknown_b [file] =>
C:\xampp\htdocs\monolog-test\test-error.php [line] => 4 )

The function error_get_last will get the last error in the stack trace. This can be used to
remove all the other errors displayed in the stack trace and only focus on the last error that
has occurred.

// will log to the web server error log file, will also log to Retrace
error_log("This is a sample error.", 0);

// will email the error log


error_log("This is a sample error.", 1, "[email protected]");

// will log an error to a specified file


error_log("This is a sample error.", 3, "my-errors.log");

The error_log function allows developers to log errors in either the default error log of the
web server, send the error log to an email, or log the error to a specified file.

$divisor = 0;
if ($divisor == 0) {
trigger_error("Division of zero not allowed!", E_USER_ERROR);
}

Fatal error: Division of zero not allowed! in C:\xampp\htdocs\monolog-test\test-error.php on


line 5

This will generate a user defined error, notice, warning etc. This PHP function allows
developers to generate a specified response at runtime.

Other PHP framework error handling

In other PHP frameworks, error handling is a lot easier and most of them are just a matter of
editing the configuration file. In Laravel, the class App\Exceptions\Handler handles all the
triggered exceptions and logging by a web application. The Handler class in Laravel has two
methods, report and render. The report method is used to send exceptions to an external
service. The report is good for logging errors without displaying it in a web page. The render
method will convert an exception into an HTTP response that needs to be sent back to the
browser.

abort(500);
abort(403, 'You are not allowed to enter!');

Throwing HTTP exceptions can easily be done in Laravel by using the abort helper. The
abort helper function has an optional response text parameter for a custom display message.

PHP Security Function: strip_tags, filter_var, Md5 and sha1


Potential security threats
Your System is attacked by basically two groups of people:

 Users –The users enter wrong parameters which put a negative effect on a web application or
website.
 Hackers -Hackers intentionally disrupt the application and intentionally gain access to
unauthorized data
These are the following kinds of attack:

Cross-site scripting – This kind of attack inserts a harmful code usually in JavaScript. This
can be done by using user input forms like comments forms and contact us.

1. It can be used to collect retrieve sensitive information such as cookies data.


2. It can be used to redirect the user to another website or a different URL.
3. Other threats – Shell Injection, PHP code injection, Email Injection.

SQL Injection – This Kind of attack adds harmful code to SQL statements. This can be
executed either from user input forms or URLs that use variables.

The code is being added code comments the condition in the WHERE clause of an SQL
statement.

1. Insert- It inserts that type of a condition that will always be true.


2. Delete –It deletes data from a table.
3. Update –It Update data in a table.
4. This Kind of attack is usually used to gain unauthorized access to an application.

PHP Application Security Tips:


Now let's look at some of the PHP Security Tips that we must to know consider when
developing our applications:

PHP strip_tags
This strip_tags functions removes JavaScript, HTML or PHP tags from a string.

This function is useful to protect our applications from attacks such as cross site scripting.
Let’s take an example of an application that accepts comments from users.

<?php
$user_input = "phptpoint is Awesome";
echo "<h4>This is my Commenting System</h4>";
echo $user_input;
?>

Assuming you have saved comments.php "if you use XAMPP" you can do that in you
htdocs folder

Let's assume you receive the following as the user input <script>alert('welcome to
phptpoint!');</script>

<?php
$user_input = "<script>alert('welcome to phptpoint!');</script>";
echo "<h4>This is my Commenting System</h4>";
echo $user_input;
?>

Browse to the URL http://localhost/demo/comments.php

Let's now secure our application from such attacks using strip_tags function.
<?php
$user_input = "<script>alert('hello phptpoint!');</script>";
echo strip_tags($user_input);
?>

Browse to the URL http://localhost/demo/comments.php

PHP filter_var function


The filter_var function is used to for data validation and sanitization.

If the data is of the right type then you can check the validation and you will get the false
result while checking numeric validation on a string.

For complete reference check this link filter_var.

Sanitization helps to remove illegal characters from a string.

It uses the filter_var function and FILTER_SANITIZE_STRIPPED constant to strip tags


or encode unwanted characters. This filter helps to removes data that can be potentially
harmful for your application.

Let's take an example:

<?php
$user_input = "<script>alert('Your site sucks!');</script>";
echo filter_var($user_input, FILTER_SANITIZE_STRIPPED);
?>

Mysql_real_escape_string function - This function protect an application against SQL


injection and used to create a legal SQL string.

Let's take an example that we have the SQL statement for validating the user id and
password.

<?php
SELECT userid,pswd,role FROM users WHERE userid = 'admin' AND password = 'pass';
?>
A vicious user can enter the following code in the user login box.„OR‟ 1 = 1- And abcd in the password
text box , below is the authentication code module.
<?php
$userid = "' OR 1 = 1 -- ";
$pswd = "abcd";
$sql = "SELECT userid,pswd,role FROM users WHERE userid = '$userid' AND password = '$pswd';";
echo $sql;
?>

Output:
SELECT userid,pswd,role FROM users WHERE userid = '' OR 1 = 1 -- ' AND password = abcd;

HERE,

1. "SELECT * FROM users WHERE user_id = ''" tests for an empty user id".
2. "OR 1 = 1 " is a condition that will always be true.
3. "--" comments that part that tests for the password.

Let's now use mysql_real_escape_string function to secure login module.

<?php
$userid = mysql_real_escape_string("' OR 1 = 1 -- ");
$pswd = mysql_real_escape_string("abcd");
$sql = "SELECT userid,pswd,role FROM users WHERE userid = '$userid' AND password = '$pswd';";
echo $sql;
?>

Output:
SELECT userid,pswd,role FROM users WHERE userid = '\' OR 1 = 1 -- ' AND password = abcd;

PHP Md5 and PHP sha1.


Sha1 is the acronym for secure Hash Algorithm 1 and Md5 is the acronym for Message
Digest 5.

Both the acronym are used to encrypt strings.

When in case a string has been encrypted, it is tedious to decrypt it.

When storing in passwords in the database Md5 and sha1 are very useful.

The code below shows the implementation of md5 and sha1

<?php
echo "MD5 Hash: " . md5("password");
echo "SHA1 Hash: " . sha1("password");
?>

Assuming you have saved the file hashes.php in in your folder, browse to the URL

You might also like