Monday, July 13, 2026

Sending email from website using Microsoft Office 365 OAuth2


Step 1: Register an Application in Microsoft Entra ID

  1. Sign in to the Microsoft Azure portal:

    Microsoft Azure Portal

  2. Navigate to:

    Microsoft Entra ID → App registrations → New registration

  3. Configure:

    • Name: My Email Application

    • Supported account types:

      • Usually Accounts in this organizational directory only

    • Redirect URI:

      • Web: http://localhost:8080/callback

      • (Can be changed later)

  4. Click Register.


Step 2: Create a Client Secret

  1. Open your app registration.

  2. Go to:
    Certificates & Secrets → New client secret

  3. Enter a description.

  4. Choose expiry period.

  5. Click Add.

  6. Copy and save:

    • Client Secret Value

    • Application (Client) ID

    • Directory (Tenant) ID


Step 3: Add API Permissions

Go to:

API Permissions → Add Permission → Microsoft Graph

Add delegated permissions:

  • offline_access

  • openid

  • profile

  • Mail.Send

Click Grant Admin Consent if required.


Step 4: Generate Authorization URL

Replace placeholders:

https://login.microsoftonline.com/TENANT_ID/oauth2/v2.0/authorize
?client_id=CLIENT_ID
&response_type=code
&redirect_uri=http://localhost:8080/callback
&response_mode=query
&scope=offline_access Mail.Send

Example:

https://login.microsoftonline.com/xxxxxxxx/oauth2/v2.0/authorize?client_id=yyyyyyyy&response_type=code&redirect_uri=http://localhost:8080/callback&response_mode=query&scope=offline_access%20Mail.Send

Open this URL in a browser.


Step 5: Sign In and Grant Consent

  1. Log in with the Office 365 mailbox account.

  2. Accept permissions.

  3. Microsoft redirects to:

http://localhost:8080/callback?code=LONG_AUTH_CODE

Copy the value of code.


Step 6: Exchange Authorization Code for Refresh Token

Using cURL:

curl -X POST \
https://login.microsoftonline.com/TENANT_ID/oauth2/v2.0/token \
-d "client_id=CLIENT_ID" \
-d "client_secret=CLIENT_SECRET" \
-d "grant_type=authorization_code" \
-d "code=AUTHORIZATION_CODE" \
-d "redirect_uri=http://localhost:8080/callback"

Response:

{
  "token_type": "Bearer",
  "expires_in": 3599,
  "access_token": "...",
  "refresh_token": "0.AAAA...."
}

Copy the value of:

refresh_token

Step 7: Configure Your Application

For a CodeIgniter 4 application, place it in .env:

office365.clientId=YOUR_CLIENT_ID
office365.clientSecret=YOUR_CLIENT_SECRET
office365.tenantId=YOUR_TENANT_ID
office365.refreshToken=YOUR_REFRESH_TOKEN

Or in your custom configuration file:

public string $clientId = '...';
public string $clientSecret = '...';
public string $tenantId = '...';
public string $refreshToken = '...';

Step 8: Test Token Refresh

Test manually:

curl -X POST \
https://login.microsoftonline.com/TENANT_ID/oauth2/v2.0/token \
-d "client_id=CLIENT_ID" \
-d "client_secret=CLIENT_SECRET" \
-d "grant_type=refresh_token" \
-d "refresh_token=YOUR_REFRESH_TOKEN"

If successful, Microsoft returns a new access token.



Sunday, July 12, 2026

Vue Codeigniter Integration

Let CodeIgniter serve the initial HTML page, and let Vue mount into a <div id="app"></div>. This gives you the benefits of CodeIgniter routing, sessions (Shield), CSRF, SEO-friendly pages, and future API/mobile support.

Recommended Project Structure

project-root/
├── app/
│   ├── Controllers/
│   │   └── Home.php
│   └── Views/
│       └── welcome_message.php
│
├── public/
│   ├── build/
│   │   ├── assets/
│   │   └── .vite/
│   ├── index.php
│   └── favicon.ico
│
├── frontend/
│   ├── src/
│   │   ├── main.js
│   │   ├── App.vue
│   │   └── router/
│   ├── index.html
│   └── vite.config.js

1. Build Vue

npm run build

This generates

public/build/
    assets/
        index-xxxxx.js
        index-xxxxx.css

2. Create the CodeIgniter View

app/Views/welcome_message.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <?= vite('frontend') ?>
</head>
<body>

<div id="app"></div>

</body>
</html>

3. Home Controller

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
        return view('welcome_message');
    }
}

4. Routes

$routes->get('/', 'Home::index');

Now visiting

http://localhost/

loads the CI page.


5. Vue Entry

src/main.js

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

Vue will mount inside

<div id="app"></div>

6. During Development (Vite)

Instead of loading the built assets, load the Vite development server.

Create a helper:

<?php

function vite(string $entry = 'frontend')
{
    if (ENVIRONMENT === 'development')
    {
        return '
            <script type="module" src="http://localhost:5173/@vite/client"></script>
            <script type="module" src="http://localhost:5173/src/main.js"></script>
        ';
    }

    $manifest = json_decode(
        file_get_contents(FCPATH.'build/.vite/manifest.json'),
        true
    );

    $file = $manifest['src/main.js'];

    $html = '';

    if (isset($file['css'])) {
        foreach ($file['css'] as $css) {
            $html .= '<link rel="stylesheet" href="'.base_url('build/'.$css).'">';
        }
    }

    $html .= '<script type="module" src="'.base_url('build/'.$file['file']).'"></script>';

    return $html;
}

Then

<?= vite() ?>

works in both development and production.


7. Vue Router

Configure history mode.

import { createRouter, createWebHistory } from 'vue-router'

export default createRouter({
    history: createWebHistory(),
    routes: [
        // routes
    ]
})

Register it:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App)
    .use(router)
    .mount('#app')

8. Catch All Routes in CodeIgniter

If Vue Router handles navigation, make CodeIgniter always return the same view:

$routes->get('/', 'Home::index');

$routes->get('(:any)', 'Home::index');

or

$routes->add('(:any)', 'Home::index');

This allows routes like

/
/about
/products
/dashboard

to all load the Vue application.


9. CodeIgniter + Shield Authentication

Since CodeIgniter serves the page:

  • Shield sessions work normally.

  • CSRF protection remains available.

  • You can expose authenticated user data to Vue before it mounts if needed:

<script>
window.App = {
    user: <?= json_encode(auth()->user()) ?>
};
</script>

Then in Vue:

const user = window.App.user;

Architecture Recommendation

For CodeIgniter 4 + Vue + TailwindCSS + CodeIgniter Shield application (with future mobile API support), a clean architecture is:

Browser
   │
   ▼
CodeIgniter Route
   │
   ▼
Home Controller
   │
   ▼
welcome_message.php
   │
   ├── <div id="app"></div>
   ├── Inject authenticated user/session data
   └── Load Vite-built JS/CSS
            │
            ▼
         Vue App
            │
      Vue Router
            │
      Axios/Fetch API
            │
            ▼
CodeIgniter REST API
            │
      Shield Authentication
            │
        Database

This keeps CodeIgniter responsible for the initial request, authentication, and APIs, while Vue handles the entire client-side UI, which is scalable and aligns well with a future mobile application consuming the same REST APIs.

Wednesday, January 8, 2025

Codeigniter Shield Authorization

Codeigniter Shield Authorization

CodeIgniter Shield is the official authentication and authorization framework for CodeIgniter 4. It provides a flexible role-based access control (RBAC) system, allowing you to manage user permissions effectively.

Key Concepts:

Groups: Users can belong to multiple groups, which can represent traditional roles (e.g., admin, moderator) or be used to group users based on features or other criteria.

Permissions: Permissions define what actions a user is allowed to perform within your application. Permissions are typically associated with groups.

Users: Each user has a set of permissions based on the groups they belong to, and can also have permissions directly assigned to them.

Defining Groups:

Groups are defined in the Shield\Config\AuthGroups configuration file. Each group has a key, a title, and an optional description.

php
public array $groups = [
'superadmin' => [
'title' => 'Super Admin',
'description' => 'Optional description of the group.',
],
'editor' => [
'title' => 'Editor',
'description' => 'Can edit content.'
],
'user' => [
'title' => 'User',
'description' => 'Basic user access.'
]
];

Defining Permissions:

php
public array $permissions = [ 'superadmin.access' => 'Can access the sites admin area', 'superadmin.settings' => 'Can access the main site settings', 'editor.create' => 'Can view/edit site content', 'users.create' => 'Can create new non-admin users', 'users.edit' => 'Can edit existing non-admin users', 'users.delete' => 'Can delete existing non-admin users', ];

Checking Permissions:

You can check if a user has a specific permission using the can() method on the User entity. This method checks permissions within the groups the user belongs to, as well as any permissions directly assigned to the user.

php
if (! auth()->user()->can('users.create')) {
return redirect()->back()->with('error', 'You do not have permissions to access that page.');
}

Example:

Let's say you have a 'superadmin' group with the permission users.create. You can check if the current user has this permission like this:

php
if (auth()->user()->can('users.create')) {
// Allow user to create a new user
} else {
// Redirect or show an error message
}

Getting the Current User:

You can get the current user using the auth() helper function:

php
$user = auth()->user();

Adding Group To a User:

php
$user = auth()->user();
$user->addGroup('superadmin', 'editor');

Removing Group From a User:

php
$user = auth()->user(); $user->removeGroup('superadmin', 'editor');

Check if User Belongs to a Group:

php
$user = auth()->user(); if ($user->inGroup('superadmin')) { // do something }

In summary, CodeIgniter Shield's authorization system allows you to:

Define user groups with specific roles and permissions.

Assign users to one or more groups.

Check if a user has the necessary permissions to perform an action.

This provides a flexible and robust way to manage access control in your CodeIgniter application.

Advertisement

JBL Wave Buds 2 Ear Buds Wireless BluetoothV5.3, Active Noise Cancellation EarBuds,Multi Connect, App for Customized Extra Bass Eq, Relax Mode,Speed Charge, 40H Playback, Fast Pair, 4 Mics,IP54(Black)

Sony WF-C710N | Dual Noise Cancellation Wireless Bluetooth in Ear Earbuds | AI Call Quality | 40Hrs Battery W/O ANC | 30Hrs Battery with ANC - Blue

Thursday, March 21, 2024

Electron app with React and Electron Forge

Build Desktop applications with React and Electron Forge

Create cross-platform desktop applications using modern web development tools and integration of third-party libraries and frameworks with Electron. Build your electron apps with the commonly used web technologies like HTML, JavaScript, CSS. Supports native interface for all platforms like windows, macOS, Linux. Integrate JavaScript frameworks such as React, Vue for front-end tooling. Publish electron apps with built-in templates. Currently Electron apps have support for these templates for publishing,

  1. Vite
  2. Webpack

Monday, March 11, 2024

Codeigniter Shield - Install and Configure

Install Codeigniter Shield

Codeigniter Shield is the official authentication and authorization framework for codeigniter 4. It provides session authentication, in which the user ID and password is stored in the session for the subsequent requests to authenticate against. Basically, it has all the features that the modern website offers.

Tuesday, March 5, 2024

Codeigniter in Visual Studio Code - Getting started

Getting started with Codeigniter in VSCode

Codeigniter is a PHP Framework for building robust and flexible websites. Basically, codigniter can be downloaded from official sources as a zip package and install in your system to start development. But, there are other ways to download and install codeigniter to build web applications. Here, we will demonstrate two ways to get started with codeigniter app development in visual studio code. The two approaches used here are,

  1. Clone Git repository
  2. Composer (tool to install packages and dependencies)

Monday, March 4, 2024

Setup Laravel in Visual Studio Code - Getting started

Setup Laravel in Visual Studio Code

Laravel is a very popular PHP Framework for developing web applications. There are many ways to get started with Laravel development in different platforms. But, the most commonly used IDE by developers is visual studio code because it is open source and has support for multiple languages. It even has extensions enabling to integrate third-party tools and services, thus allows for faster development. Here, two approaches are used to download and install Laravel in vscode.

  1. Clone Git repository
  2. Composer (tool to get packages and dependencies)


After you download Laravel, first thing that you have to is create a .env file and copy the configurations from the .env.example to .env file. Then, Generate app key and assign to the setting variable.

Advertisement

Thursday, February 29, 2024

Install WordPress on IIS (Internet Information Services)

Install WordPress on IIS

WordPress is an open-source Content Management System (CMS) built using core PHP. It is a production ready web application package which can be setup in minutes to publish content for the end users. Administrators have complete control over the information being displayed on the site. Managing all aspects of the site is made possible through admin panel.


Deploying WordPress on IIS requires you to configure IIS Manager to handle PHP requests. In order to handle PHP requests enable CGI module from windows features. Install PHP package and register in IIS Manager using PHP Manager for IIS, which is a tool to manage different versions of PHP.

Wednesday, February 14, 2024

Configure Visual Studio Code for PHP development using IIS Express

Setup VS Code for PHP Development using IIS Express

Visual studio code has been the preferred IDE for software development among the developers and the most popular because of the support for building software in multiple languages and platforms, third-party extensions that boosts productivity. Developing PHP applications in visual studio code requires configuring it to handle PHP requests. 

First, you need to have PHP installed on your machine. In VS Code, open the settings and set the path to the PHP executable in the validation setting.

Next, to configure IIS Express settings download and install IIS Express which is a lightweight web server for development purposes. In the VS Code settings set the path to the executable for both iisexpress Appcmd and iisexpress.

Friday, August 20, 2021

Trigger function in DIV

 How to trigger function in DIV

The events in the object fires when the page loads, mouse events , keyboard events and other types of inputs. It is not possible to trigger an event in the DIV for example, onload event when the object is loaded. Some elements like body, script, link, image, style support firing up of events. However, it is required for the developer to trigger the event in object DIV. In order to do that we can use jquery trigger method to fire the event.

HTML

<div onload="$(this).text('I will display in Div using text()');"></div>
<div onload="welcome()"></div>

Javascript/Jquery

function welcome(){
alert('Hello world! in func welcome');
}

$(function(){
$('div[onload]').trigger('onload');
});

Friday, September 11, 2020

Move column data from one table to another

There may be situations when you want to move MYSQL column data from one table to another. 

MySQL Query: 

UPDATE accounts_users, accounts_membership  SET accounts_users.username=accounts_membership.username WHERE accounts_users.user_id=accounts_membership.user_id AND accounts_users.user_id >= 1;

Thursday, June 4, 2020

Retrieve duplicate column values in MySQL

How to find duplicate column values in MySQL

Let's see some of the many ways to retrieve duplicate column value from MySQL table. In this example, we are going to find and return duplicate contact names from the contacts table. It is up to you to decide which is applicable according to the scenario.

Approach 1:

SELECT customer_name FROM contacts group by customer_name having count(*) > 1;

OR

SELECT 
    customer_name, 
    COUNT(customer_name)
FROM
    contacts
GROUP BY customer_name
HAVING COUNT(customer_name) > 1;

Result:

Approach 2:

SELECT contact_id, 
   contact_type, 
   contacts.customer_name 
FROM contacts
   INNER JOIN (SELECT customer_name
               FROM   contacts
               GROUP  BY customer_name
               HAVING COUNT(contact_id) > 1) dup
           ON contacts.customer_name = dup.customer_name;

Result:

Monday, May 25, 2020

Export to excel using PHP and Jquery

Export to excel using PHP and Jquery

In order to export MySQL table data to excel let's create a HTML page and put two anchor tags, one is to export to excel and the other to export to CSV (Comma Seperated Value). Write a jquery function to submit the form which makes call to the PHP function to export data returned to excel.


HTML Page
<form id="site" method="post" enctype="multipart/form-data">
  <div>
    <a id="studentsExportExcel" href="javascript:void(0)" onclick="exportExcel(this)">Export to excel (.xls)</a>
    <a id="studentsExportCSV" href="javascript:void(0)" onclick="exportExcel(this)">Export to csv</a>
  </div>
  <input type="hidden" value="" id="hidden-type" name="studentsExportType"/>
</form>
Jquery
$(document).ready(function () {
	function exportExcel(obj) {
    	var target = $(obj).attr('id');
    	switch (target) {
        case 'studentsExportExcel':
        case 'studentsExportCSV':
            $('#hidden-type').val(target);
            $('#site').submit();
            $('#hidden-type').val('');
            break;
    	}
	}
});
PHP Function
public function students()
    {
        if(isset($_POST["studentsExportType"]))
        {
            switch($_POST["studentsExportType"])
            {
                case "studentsExportExcel" :
                    // Submission from
                    $filename = "students". date('dMY') .".xls";       
                    header("Content-Type: application/vnd.ms-excel");
                    header("Content-Disposition: attachment; filename=\"$filename\"");
                    students_export_excel();
                    $_POST["studentsExportType"] = '';
                    exit();
                case "studentsExportCSV":
                    $filename = "students". date('dMY') . ".csv";
                    header("Content-type: application/csv");
                    header("Content-Disposition: attachment; filename=\"$filename\"");
                    header("Pragma: no-cache");
                    header("Expires: 0");

                    $handle = fopen('php://output', 'w');
                    $data = get_students();
                    foreach ($data as $data)
                    {
                        fputcsv($handle, $data);
                    }
                    fclose($handle);
                    exit();
                default :
                    die("Unknown action : ".$_POST["action"]);
                    break;
            }
        }
    }


function students_export_excel()
    {
        $heading = false;
        $students = get_students();
        
        if(!empty($students))
          foreach($students as $row) {
            if(!$heading) {
              // display field/column names as a first row
              echo implode("\t", array_keys($row)) . "\n";
              $heading = true;
            }
            echo implode("\t", array_values($row)) . "\n";
          }
        exit;
    }


function get_students()
{
        $servername = "localhost";
        $username = "username";
        $password = "password";
        $dbname = "myDB";
 
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
 
        $sql = "SELECT id, firstname, lastname FROM students";
        $result = $conn->query($sql);
 
        return $result;
}

Monday, May 18, 2020

Sum columns in multiple tables - MySQL

How to sum columns in multiple tables in MySQL

We will see two methods to sum columns from multiple tables. The first method is more preferred than the second method. Therefore consider using first approach.


METHOD 1:
SELECT credit.contact_id, (IFNULL(credit, 0) - IFNULL(debit, 0)) as balance
     FROM (
    (SELECT SUM(credit) as credit, contact_id FROM table_a GROUP BY contact_id) as credit
       LEFT JOIN
    (SELECT SUM(debit) as debit, contact_id FROM table_b GROUP BY contact_id) as debit
     ON debit.contact_id = credit.contact_id);
METHOD 2:
SELECT contact_id, SUM(balance) FROM
    (SELECT contact_id ,credit as balance FROM table_a
       UNION ALL
    SELECT contact_id,- debit as balance FROM table_b
   ) as x
  GROUP BY contact_id;

Ads
Serplex® 180-IN-1 Precision Screwdriver Set with 3 Torque Modes and 162 Magnetic Precision Bits
XERGY LED Desk Lamp with USB Charging Output – Dimmable, Touch Control, Timer, Night Mode, 5 Color Modes

Saturday, May 2, 2020

Infinite scroll for div element

Infinite scroll loading for div element

This article explains how to incrementally load items as you scroll down div element in the page. In this example a HTML page is created with an unordered list element where the list items returned by the function gets appended. Here difference of the scroll height of the div container and its client height is compared against the scroll top offset value.

HTML Page
<div>
  <div id="containerName" style="overflow: scroll;height: 500px;"></div>
  <div style="text-align: center;"><img alt="Loading..." src="../assets/images/svg/three-dots.svg" class="loading-info" /></div>
  <div id="notifyMessage"></div>
</div>
Jquery
$(document).ready(function () {
  var offset = 0;
  var loading = false;
  $('.loading-info').hide();
  appendItems(offset, loading);
  $(window).scroll(function () {
        if ($('#notifyMessage').html() === "") {
            var divHeight = $('#containerName')[0].scrollHeight - $('#containerName')[0].clientHeight;
            if ($('#containerName').scrollTop() === divHeight) {
                offset += 20; appendItems(offset, loading); } } });
});
function appendItems(offset, loading) {
    if (loading == false) {
        loading = true;
        $('.loading-info').show();
        $.post('/admin/items/append', { 'offset': offset }, function (data) {
            loading = false;
            if (data.trim().length == 0) {
                $('.loading-info').hide();
                $('#notifyMessage').html('<p> End of records</p>');
                return;
            }
            $('.loading-info').hide();
 
            $("#containerName").append(data);
        }).fail(function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        })
    }
}
PHP Function
function append()
{
        $list = NULL;
        $offset = $_POST['offset'];
        $servername = "localhost";
        $username = "username";
        $password = "password";
        $dbname = "myDB";
 
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
 
        $sql = "SELECT id, firstname, lastname FROM employees limit $offset, 20";
        $result = $conn->query($sql);
 
        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                $list +=  "<div>id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "</div>";
            }
        } 
        $conn->close();
 
        echo $list;
}

Scroll Loading using Jquery and PHP

Scroll loading using jquery and PHP

This article explains how to incrementally load items as you scroll down the page. In this example a HTML page is created with an unordered list element where the list items returned by the function gets appended.

HTML Page
<div>
  <ul id="containerName"></ul>
  <div style="text-align: center;"><img alt="Loading..." src="../assets/images/svg/three-dots.svg" class="loading-info" /></div>
  <div id="notifyMessage"></div>
</div>
Jquery
$(document).ready(function () {
  var offset = 0;
  var loading = false;
  $('.loading-info').hide();
  appendItems(offset, loading);
  $(window).scroll(function () {
        if ($('#notifyMessage').html() === "") {
            if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
                offset += 20;
                appendItems(offset, loading);
            }
        }
    });
});
function appendItems(offset, loading) {
    if (loading == false) {
        loading = true;
        $('.loading-info').show();
        $.post('/admin/items/append', { 'offset': offset }, function (data) {
            loading = false;
            if (data.trim().length == 0) {
                $('.loading-info').hide();
                $('#notifyMessage').html('<p> End of records</p>');
                return;
            }
            $('.loading-info').hide();
 
            $("#containerName").append(data);
        }).fail(function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        })
    }
}
PHP Function
function append()
{
        $list = NULL;
        $offset = $_POST['offset'];
        $servername = "localhost";
        $username = "username";
        $password = "password";
        $dbname = "myDB";
 
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
 
        $sql = "SELECT id, firstname, lastname FROM employees limit $offset, 20";
        $result = $conn->query($sql);
 
        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                $list +=  "<li>id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "</li>";
            }
        } 
        $conn->close();
 
        echo $list;
}

Tuesday, April 28, 2020

HTML Scalar Vector Graphics(SVG)

Left/Right Half Circle Using SVG

<svg width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="grey" />
  <path d="M50,0 a1,1 0 100,100 0,0" fill="orange" />
</svg>

Bottom/Top Half Circle Using SVG

<svg width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="grey" />
  <path d="M0,50 a1,1 0 0,0 100,0" fill="orange" />

</svg>

Sending email from website using Microsoft Office 365 OAuth2

Step 1: Register an Application in Microsoft Entra ID Sign in to the Microsoft Azure portal: Microsoft Azure Portal Navigate to: Microsoft E...