Dive into Web Development with PHP Your Complete Guide

Advanced PHP Techniques Optimizing Performance and Security in Development.

Strat Your Test Now Dear learners, Are you interested in assessing your progress? Request your mentor to give you access and start your Test.

“Explore PHP through comprehensive online courses, covering fundamentals to advanced topics. Gain practical skills in web development, database integration, and dynamic content creation. Learn efficiently with expert instructors.”

Learn More About PHP

1. Object-Oriented Programming (OOP) :

  • Classes and objects in PHP.

Classes:

  • A class is a blueprint for creating objects (instances) in PHP.
  • It defines the properties (variables) and methods (functions) that the objects will have.
  • Classes provide a way to organize related data and behavior into a single unit.

Objects:

  • An object is an instance of a class.
  • It represents a specific entity with its own set of properties and behaviors.
  • Objects allow you to work with instances of classes, accessing their properties and calling their methods.

PHP

class Car {
// Properties
public $make;
public $model;
public $year;

// Constructor
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}

// Method
public function getInfo() {
return "Make: {$this->make}, Model: {$this->model}, Year: {$this->year}";
}
}

PHP

// Creating objects of the Car class
$car1 = new Car(“Toyota”, “Camry”, 2022);
$car2 = new Car(“Honda”, “Civic”, 2021);

// Accessing properties
echo $car1->make; // Output: Toyota

// Calling methods
echo $car2->getInfo(); // Output: Make: Honda, Model: Civic, Year: 2021

Summary:

Classes are blueprints for creating objects, defining their properties and methods.
Objects are instances of classes, representing specific entities with their own characteristics and behaviors.
Inheritance allows classes to inherit properties and methods from another class, facilitating code reuse and extending functionality.

PHP

class ElectricCar extends Car {
// Additional property
public $range;

// Constructor
public function __construct($make, $model, $year, $range) {
parent::__construct($make, $model, $year);
$this->range = $range;
}

// Overriding method
public function getInfo() {
return parent::getInfo() . ", Range: {$this->range} miles";
}
}

// Creating an object of the ElectricCar class
$electricCar = new ElectricCar("Tesla", "Model S", 2023, 350);

// Accessing method
echo $electricCar->getInfo(); // Output: Make: Tesla, Model: Model S, Year: 2023, Range: 350 miles
}

OUTPUT

Inheritance, encapsulation, and polymorphism: In PHP, inheritance, encapsulation, and polymorphism are key concepts of object-oriented programming (OOP). Here’s an overview of each concept along with examples:

1. Inheritance:

Inheritance allows a class (subclass) to inherit properties and methods from another class (superclass). This promotes code reuse and facilitates the creation of a hierarchy of classes.

PHP

class Animal {
    public $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function speak() {
        return "Animal sound";
    }
}

class Dog extends Animal {
    public function speak() {
        return "Woof!";
    }
}

// Creating objects
$animal = new Animal("Generic Animal");
$dog = new Dog("Rex");

// Calling methods
echo $animal->speak();  // Output: Animal sound
echo $dog->speak();     // Output: Woof!

OUTPUT

Animal sound

Woof !

2. Encapsulation:

Encapsulation is the bundling of data (properties) and methods that operate on that data into a single unit (class). It helps in hiding the internal state of an object and only exposes the necessary functionality.

PHP

class Car {
    private $model;

    public function setModel($model) {
        $this->model = $model;
    }

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

// Creating object
$car = new Car();

// Setting model
$car->setModel("Toyota Camry");

// Getting model
echo $car->getModel();  // Output: Toyota Camry

OUTPUT

Toyota Camry

3. Polymorphism:

Polymorphism allows objects of different classes to be treated as objects of a common superclass. This means that a method defined in the superclass can be overridden in a subclass to provide different behavior.

  • Inheritance: Dog inherits from Animal.
  • Encapsulation: $model property is encapsulated within the Car class.
  • Polymorphism: Different implementations of calculateArea() method in Rectangle and Circle classes.

PHP

class Shape {
    public function calculateArea() {
        return "Area not defined for generic shape";
    }
}

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

class Circle extends Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * $this->radius * $this->radius;
    }
}

// Creating objects
$rectangle = new Rectangle(5, 4);
$circle = new Circle(3);

// Calculating areas
echo $rectangle->calculateArea();  // Output: 20
echo $circle->calculateArea();     // Output: 28.274333882308

OUTPUT

 20
 28.274333882308

Error Handling:

  1. Understanding and implementing error handling :
    • Error handling in PHP involves managing and handling errors, exceptions, and notices that occur during the execution of PHP scripts. Here’s an overview of error handling and how to implement it in PHP:

      Types of Errors in PHP:

      1. Syntax Errors: These occur when there’s a mistake in the syntax of the PHP code.
      2. Runtime Errors: Also known as exceptions, these occur during the execution of the script due to invalid operations or unexpected conditions.
      3. Notices and Warnings: These are non-fatal errors that occur during script execution, such as accessing undefined variables or including missing files.

      Implementing Error Handling in PHP:

      1. Error Reporting Levels:

      PHP provides error reporting levels that determine which errors are reported and how they are reported. You can set the error reporting level in your PHP script using error_reporting() function.

// Set error reporting level to report all errors

error_reporting(E_ALL);

2. Displaying Errors:

During development, it’s often useful to display errors directly on the webpage. This can be done by setting display_errors directive in the php.ini file or using ini_set() function in your script.

// Display errors directly on the webpage

ini_set(‘display_errors’, 1);

3. Custom Error Handling:

PHP allows you to define custom error handling functions using set_error_handler() function. This allows you to handle errors in a custom way, such as logging errors to a file or sending an email notification.

PHP

  // Custom error handling function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    // Log error to a file
    $logMessage = "Error: [$errno] $errstr in $errfile on line $errline";
    error_log($logMessage, 3, "error.log");

    // Display custom error message
    echo "An error occurred. Please try again later.";

    // Prevent default error handling
    return true;
}

// Set custom error handler
set_error_handler("customErrorHandler");

OUTPUT

4. Exception Handling:

For handling exceptions, PHP provides try-catch blocks. Code that may throw exceptions is placed within the try block, and if an exception occurs, it’s caught and handled in the catch block.

PHP

 try {
    // Code that may throw exceptions
    throw new Exception("An error occurred.");
} catch (Exception $e) {
    // Handle the exception
    echo "Caught exception: " . $e->getMessage();
}

OUTPUT

5. Error Logging:

Logging errors to a file is a common practice in PHP error handling. This helps in debugging and troubleshooting issues in production environments.

PHP

// Log error to a file
$errorLogMessage = "Error: [$errno] $errstr in $errfile on line $errline";
error_log($errorLogMessage, 3, "error.log");

OUTPUT

Using try, catch, and finally blocks.
  • In PHP, try-catch blocks are used for exception handling. The try block contains the code that may throw an exception, and the catch block handles the exception if one is thrown. Additionally, you can use the finally block to specify code that should be executed regardless of whether an exception is thrown or not. Here’s how to use try-catch and finally blocks in PHP:

Summary:

  • try block contains the code that may throw an exception.
  • catch block catches the exception and handles it.
  • finally block contains code that should always be executed, regardless of whether an exception is thrown or not.

Using try-catch Blocks:

try {
// Code that may throw an exception
$result = 10 / 0; // This will throw a division by zero error
} catch (Exception $e) {
// Handle the exception
echo "Caught exception: " . $e->getMessage();
}

Using finally Block:

try {
    // Code that may throw an exception
    $result = 10 / 2;
    echo "Result: $result";
} catch (Exception $e) {
    // Handle the exception
    echo "Caught exception: " . $e->getMessage();
} finally {
    // Code that should always be executed, regardless of whether an exception is thrown or not
    echo "This will always be executed.";
}

Reading and writing files with PHP :

  • In PHP, you can read from and write to files using various functions provided by the language. Here’s how you can perform file operations in PHP:
    Reading Files:

Reading Entire File Into a String:

$filename = “example.txt”;
$content = file_get_contents($filename);
echo $content;

Reading File Line by Line:

$filename = "example.txt";
$handle = fopen($filename, "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line;
    }
    fclose($handle);
} else {
    echo "Unable to open file.";
}
  • Writing Files:

(Overwriting Existing Content):

$filename = “example.txt”;
$content = “Hello, world!”;
file_put_contents($filename, $content);

file_put_contents($filename, $content, FILE_APPEND);

Writing to a File Line by Line:

$filename = "example.txt";
$content = "New line\n";
$handle = fopen($filename, "a");
if ($handle) {
    fwrite($handle, $content);
    fclose($handle);
} else {
    echo "Unable to open file.";
}

Summary:

  • You can read from files using functions like file_get_contents() and fopen().
  • Writing to files can be done with file_put_contents(), fwrite(), and fopen() in PHP.
  • Check file existence with file_exists() function.
  • Delete files with unlink() function.

Checking File Existence:

$filename = “example.txt”;
if (file_exists($filename)) {
echo “File exists.”;
} else {
echo “File does not exist.”;
}

Deleting Files:

$filename = "example.txt";
if (unlink($filename)) {
    echo "File deleted successfully.";
} else {
    echo "Unable to delete file.";
}

File upload and manipulation in php

File upload and manipulation in PHP involves handling file uploads from HTML forms, storing the uploaded files on the server, and performing various manipulations such as resizing images, validating file types, and saving uploaded files to a specific directory. Here’s a basic overview of how to implement file upload and manipulation in PHP:

Creating an HTML Form for File Upload:

<form action="upload.php" method="post" enctype="multipart/form-data">
Select File: <input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>

Handling File Upload in PHP (upload.php):

$targetDirectory = “uploads/”; // Specify the directory where uploaded files will be stored
$targetFile = $targetDirectory . basename($_FILES[“fileToUpload”][“name”]);

if (isset($_POST[“submit”])) {
if (move_uploaded_file($_FILES[“fileToUpload”][“tmp_name”], $targetFile)) {
echo “File uploaded successfully.”;
} else {
echo “Error uploading file.”;
}
}

Summary:

  • HTML form with enctype="multipart/form-data" is used for file upload.
  • PHP handles file upload using move_uploaded_file() function.
  • File manipulation can include resizing images, validating file types, etc.
  • Directory listing (scandir()) can be used to display uploaded files.

File Manipulation (e.g., Image Resizing):

$sourceFile = "uploads/photo.jpg";
$destinationFile = "uploads/resized_photo.jpg";

// Resizing image
list($width, $height) = getimagesize($sourceFile);
$newWidth = 100; // New width for resized image
$newHeight = ($height / $width) * $newWidth;
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
$sourceImage = imagecreatefromjpeg($sourceFile);
imagecopyresized($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Saving resized image
imagejpeg($resizedImage, $destinationFile);
imagedestroy($resizedImage);

File Type Validation:

$allowedExtensions = array("jpg", "jpeg", "png", "gif");
$uploadedFile = $_FILES["fileToUpload"]["name"];
$fileExtension = strtolower(pathinfo($uploadedFile, PATHINFO_EXTENSION));

if (!in_array($fileExtension, $allowedExtensions)) {
    echo "Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.";
}
Managing user state with cookies in php :
Setting Cookies:
You can set cookies in PHP using the setcookie() function. Cookies can be set with an expiration time, path, domain, and other optional parameters.

PHP

// Set a cookie with name “username” and value “John”
setcookie(“username”, “John”, time() + 3600, “/”); // Expires in 1 hour

OUTPUT

Reading Cookies:
You can read cookies using the $_COOKIE superglobal array. Cookies are automatically stored in this array once they are set.

PHP

// Check if the “username” cookie is set
if (isset($_COOKIE[“username”])) {
$username = $_COOKIE[“username”];
echo “Welcome back, $username!”;
} else {
echo “Welcome, guest!”;
}

OUTPUT

Welcome back, John!
Welcome, guest!

  • Modifying Cookies:

You can modify cookies by setting them again with the setcookie() function.

PHP

// Modify the value of the "username" cookie
setcookie("username", "Jane", time() + 3600, "/");

OUTPUT

Deleting Cookies:
To delete a cookie, you can set its expiration time to a past value.

PHP

// Delete the "username" cookie
setcookie("username", "", time() - 3600, "/");

OUTPUT

Cookie Parameters:
You can specify various parameters when setting cookies, such as expiration time, path, domain, and secure flag.
Summary:
  • Cookies are used to manage user state in PHP.
  • Cookies can be set, read, modified, and deleted using PHP functions.
  • Parameters such as expiration time, path, domain, and secure flag can be specified when setting cookies.
  • Cookies are stored in the $_COOKIE superglobal array once they are set, allowing easy access to their values.

PHP

// Set a cookie with custom parameters
setcookie("username", "John", time() + 3600, "/", "example.com", true, true);

OUTPUT

Implementing sessions for user authentication :

Implementing sessions for user authentication in PHP involves using session variables to track and manage user authentication status. Here’s a basic overview of how to implement user authentication using sessions in PHP:

1. Starting a Session:

You need to start a session at the beginning of each PHP script where you want to use session variables.

session_start();

2. Creating a Login Form:
Create an HTML form for user login, typically with fields for username and password.

PHP

<form action="login.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>

OUTPUT

3. Processing the Login Form (login.php):
Validate the submitted username and password against a database or any other authentication mechanism. If authentication is successful, set session variables to indicate the user is authenticated.

PHP

session_start();

// Authenticate user (e.g., check against database)
if ($_POST["username"] === "admin" && $_POST["password"] === "password") {
$_SESSION["authenticated"] = true;
$_SESSION["username"] = $_POST["username"];
echo "Login successful. Welcome, " . $_SESSION["username"];
} else {
echo "Invalid username or password.";
}

OUTPUT

Login successful. Welcome, admin
Invalid username or password.

4. Protecting Authorized Pages:

For pages that require authentication, check if the user is authenticated by verifying session variables.

PHP

session_start();

// Check if the user is authenticated
if (!isset($_SESSION["authenticated"]) || $_SESSION["authenticated"] !== true) {
    // Redirect to login page or display an error message
    header("Location: login.php");
    exit;
}

// Authorized content goes here
echo "Welcome, " . $_SESSION["username"];

OUTPUT

Welcome, John

5. Logging Out:

To log out the user, destroy session variables and end the session.

Summary:

  • Sessions in PHP are used to track user state across multiple pages.
  • Start a session using session_start().
  • Create session variables to store user authentication status and other information.
  • Authenticate users and set session variables upon successful login.
  • Protect authorized pages by checking session variables.
  • Destroy session variables and end the session to log out the user.

PHP

 session_start();

// Destroy session variables
session_unset();
session_destroy();

// Redirect to login page or display a message
echo "Logged out successfully.";

OUTPUT

"Logged out successfully."
  • Encoding and decoding JSON data :
In PHP, you can encode PHP data structures into JSON format using the json_encode() function and decode JSON strings into PHP data structures using the json_decode() function. Here’s how to encode and decode JSON data in PHP:
Encoding PHP Data to JSON:

PHP

  $data = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York"
);

// Encode PHP array to JSON format
$jsonData = json_encode($data);

// Output JSON data
echo $jsonData;

OUTPUT

{"name":"John","age":30,"city":"New York"}

Decoding JSON Data to PHP:

   $jsonData = '{"name":"John","age":30,"city":"New York"}';

// Decode JSON data to PHP array
$data = json_decode($jsonData, true);

// Access decoded data
echo "Name: " . $data['name'] . ", Age: " . $data['age'] . ", City: " . $data['city'];

OUTPUT

Name: John, Age: 30, City: New York

Error Handling:

  • When decoding JSON, you should handle errors by checking the return value of json_decode(). It returns null if the JSON data is malformed or if decoding fails.

Summary:

  • json_encode() encodes PHP data structures into JSON format.
  • json_decode() decodes JSON strings into PHP data structures.
  • Additional options can be passed to control the encoding and decoding process.
  • Error handling should be implemented to handle malformed JSON data or decoding failures.

PHP

   
$data = json_decode($jsonData);

if ($data === null) {
    echo "Error decoding JSON data.";
} else {
    // Proceed with processing decoded data
}

OUTPUT

"Error decoding JSON data."
  • Parsing and generating XML documents.
In PHP, you can parse and generate XML documents using various functions and classes provided by the language. Here’s how to parse and generate XML documents in PHP:
Parsing XML Documents:

1. SimpleXML:

SimpleXML is a PHP extension that provides a simple way to convert XML into an object. You can use it to parse XML documents and access their elements.

PHP

$xmlString = file_get_contents(“example.xml”);
$xml = simplexml_load_string($xmlString);

// Access XML elements
echo “Title: ” . $xml->title . “<br>”;
echo “Author: ” . $xml->author . “<br>”;

OUTPUT

Title: Harry Potter
Author: J.K. Rowling

2. DOMDocument:

The DOMDocument class provides a more powerful way to parse and manipulate XML documents using the Document Object Model (DOM).

PHP

$xmlDoc = new DOMDocument();
$xmlDoc->load(“example.xml”);

// Access XML elements
$title = $xmlDoc->getElementsByTagName(“title”)->item(0)->nodeValue;
$author = $xmlDoc->getElementsByTagName(“author”)->item(0)->nodeValue;

echo “Title: $title<br>”;
echo “Author: $author<br>”;

OUTPUT

Title: Harry Potter
Author: J.K. Rowling

Generating XML Documents:

1. Using SimpleXMLElement:
You can create XML documents using the SimpleXMLElement class and its methods.

PHP

$xml = new SimpleXMLElement(“<book></book>”);
$xml->addChild(“title”, “Harry Potter”);
$xml->addChild(“author”, “J.K. Rowling”);

// Output XML
echo $xml->asXML();

OUTPUT

2. Using DOMDocument:
You can create XML documents using the DOMDocument class and its methods.

PHP

$xmlDoc = new DOMDocument("1.0");
$book = $xmlDoc->createElement("book");
$xmlDoc->appendChild($book);

$title = $xmlDoc->createElement("title", "Harry Potter");
$book->appendChild($title);

$author = $xmlDoc->createElement("author", "J.K. Rowling");
$book->appendChild($author);

// Output XML
echo $xmlDoc->saveXML();
								

OUTPUT

  • SQL injection prevention.:

    Preventing SQL injection in PHP involves using parameterized queries or prepared statements instead of directly inserting user input into SQL queries. Here’s an example of how to prevent SQL injection using prepared statements in PHP:

  1. $user_input represents the data that comes from user input (e.g., a form submission).
  2. The SQL query uses a placeholder (?) instead of directly concatenating the user input into the query string.
  3. prepare() prepares the SQL query with placeholders.
  4. bind_param() binds the parameter to the prepared statement. The “s” argument specifies that the parameter is a string.
  5. execute() executes the prepared statement.
  6. get_result() retrieves the result set from the executed statement.
  7. Finally, the result is fetched and processed as needed.

Using prepared statements ensures that the user input is treated as data and not as part of the SQL query structure, effectively preventing SQL injection attacks.

PHP

connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sample input data (can come from user input)
$user_input = $_POST['user_input'];

// Using prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input); // "s" indicates the type of data, in this case, string
$stmt->execute();
$result = $stmt->get_result();

// Outputting results
while ($row = $result->fetch_assoc()) {
    // Do something with the data
    echo "Username: " . $row['username'] . "
"; } // Closing the statement and connection $stmt->close(); $conn->close(); ?>

OUTPUT

Username: john
b. Cross-site scripting (XSS) and Cross-site Request Forgery (CSRF) prevention :
  1. XSS Prevention:

To prevent XSS attacks, you should always sanitize and validate user input before displaying it on the webpage. PHP provides functions like htmlspecialchars() to encode special characters and prevent XSS attacks.

PHP

// Sanitize user input before displaying it
$user_input = htmlspecialchars($_POST['user_input']);
echo "User Input: " . $user_input;

OUTPUT

  1. CSRF Prevention:

To prevent CSRF attacks, you should generate and validate CSRF tokens for each form submission. This token should be unique for each user session and included in the form submission. Upon form submission, the server should verify the token before processing the request.

PHP

// Generate and store CSRF token in the session
session_start();
if (!isset($_SESSION[‘csrf_token’])) {
$_SESSION[‘csrf_token’] = bin2hex(random_bytes(32)); // Generate a random token
}

// Add CSRF token to the form
echo ‘<form action=”process_form.php” method=”post”>’;
echo ‘<input type=”hidden” name=”csrf_token” value=”‘ . $_SESSION[‘csrf_token’] . ‘”>’;
echo ‘<input type=”text” name=”user_input”>’;
echo ‘<input type=”submit” value=”Submit”>’;
echo ‘</form>’;

OUTPUT

  • API Integration:

Consuming and interacting with RESTful APIs :

To consume and interact with RESTful APIs in PHP, you can use the built-in cURL library or a higher-level library like Guzzle. I’ll provide an example using both methods:

  1. Using cURL:

PHP

 <?php
// Initialize cURL session
$ch = curl_init();

// Set the API endpoint URL
$url = "https://api.example.com/data";

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL session
$response = curl_exec($ch);

// Check for errors
if(curl_errno($ch)){
echo 'cURL error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);

// Process the response
$data = json_decode($response, true);
print_r($data);
?>

OUTPUT

  1. Using Guzzle:

First, you need to install Guzzle using Composer:

These examples demonstrate how to make a GET request to a RESTful API endpoint. You can customize the requests by adding headers, parameters, or handling different HTTP methods like POST, PUT, DELETE, etc., according to the API documentation.

HTML

<?php
require 'vendor/autoload.php'; // Include the Composer autoloader

use GuzzleHttp\Client;

// Create a Guzzle client
$client = new Client();

// Set the API endpoint URL
$url = "https://api.example.com/data";

// Send a GET request
$response = $client->request('GET', $url);

// Get the response body
$body = $response->getBody();

// Process the response
$data = json_decode($body, true);
print_r($data);
?>

OUTPUT

Understanding OAuth for authentication:

OAuth (Open Authorization) is a widely used protocol for authentication and authorization. It allows users to grant third-party websites or applications limited access to their resources without sharing their credentials (like passwords).

In PHP, you can implement OAuth for authentication using libraries such as OAuth 1.0a or OAuth 2.0. Here’s a high-level overview of how OAuth works and how you can implement it in PHP using OAuth 2.0:

Understanding OAuth 2.0 Workflow:

  1. Client Registration: The client (your application) registers with the OAuth server and receives a client ID and client secret.

  2. User Authorization: When a user wants to access their resources on the service provider (OAuth server), the client redirects them to the OAuth server’s authorization endpoint. The user logs in and authorizes the client’s access.

  3. Access Token Request: After authorization, the OAuth server issues an authorization code to the client. The client then exchanges this code for an access token by sending a request to the OAuth server’s token endpoint, along with the client credentials and authorization code.

  4. Accessing Protected Resources: With the access token, the client can make requests to the OAuth server’s protected resource endpoints on behalf of the user.

Implementing OAuth 2.0 in PHP:

You can use libraries like league/oauth2-client to handle OAuth 2.0 in PHP. Here’s a basic example of how to implement OAuth 2.0 client authentication using this library:

  1. Install OAuth 2.0 Client Library:

PHP

 'your_client_id',
    'clientSecret'            => 'your_client_secret',
    'redirectUri'             => 'https://your-redirect-uri',
    'urlAuthorize'            => 'https://oauth-server.com/authorize',
    'urlAccessToken'          => 'https://oauth-server.com/token',
    'urlResourceOwnerDetails' => 'https://oauth-server.com/resource',
]);

// If we don't have an authorization code, redirect the user to the authorization URL
if (!isset($_GET['code'])) {
    $authUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authUrl);
    exit;
}

// Check given state against previously stored one to mitigate CSRF attack
if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
    unset($_SESSION['oauth2state']);
    exit('Invalid state');
}

// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
    'code' => $_GET['code']
]);

// Using the access token, fetch a resource owner's details
$resourceOwner = $provider->getResourceOwner($token);

// Output the user's details
var_dump($resourceOwner->toArray());

OUTPUT

Dear learners, Are you interested in assessing your progress?
Request your mentor to give you access and start your Test.