compare and merge two array of objects

Here are two arrays which the first array is the main one and I need to update the value of every object that exist is the second array recursively by comparing their names.

Actually the first array is my form schema that might change occasionally And the second on is user filled data (schema + values). As user can update their filled forms, I need to show the new schema along with filled values of each object.

Main Array:

[
  {
    name: '6tb76sc'
  },
  {
    name: 'df45hf'
  },
  {
    name: 'ctb360f',
    childs: [
      {
        name: 'h83gus'
        childs: [
         {
           name: 'u8yh49'
         }
        ]
      }
    ]
  },
  {
    name: 'i6g7bau'
  }
]

Second Array:

[
  {
    name: '6tb76sc',
    value: 'test'
  },
  {
    name: 'ctb360f',
    childs: [
      {
        name: 'h83gus',
        value: 'test1'
        childs: [
         {
           name: 'u8yh49',
           value: 'test2'
         }
        ]
      }
    ]
  },
]

Needed output:

[
  {
    name: '6tb76sc',
    value: 'test'
  },
  {
    name: 'df45hf'
  }
  {
    name: 'ctb360f',
    childs: [
      {
        name: 'h83gus',
        value: 'test1'
        childs: [
         {
           name: 'u8yh49',
           value: 'test2'
         }
        ]
      }
    ]
  },
  {
    name: 'i6g7bau'
  }
]

Why does a fresh install of phpactor using neovim give me the following lsp error?

I’m on Windows using Neovim, and I use Mason to install all my LSPs (in this case phpactor). Below is a snippet of my setup function and the LSP Log error I’m receiving.

I can’t even try to get any further because of the error. As soon as the buffer opens, it exits with an error. I’m trying to see if I can get it to work for php and blade files as a side note. What you see below is all I have done for phpactor and nothing else so far.

lsp.lua

  ["phpactor"] = function()
      lspconfig.phpactor.setup {
          filetypes = { "php", "php_only", "blade" },
          root_dir = vim.fs.root(0, { "composer.json", ".git", "phpactor.json", "phpactor.yml" }),
          cmd = { "phpactor", "language-server" },
          init_options = {
              ["indexer.supported_extensions"] = { "blade" },
              ["language_server_completion.trim_leading_dollar"] = true,
              ["language_server_phpstan.enabled"] = false,
              ["language_server_psalm.enabled"] = false,
          }
      }
  end,

LSP Log

[ERROR][2024-10-27 15:40:28] .../vim/lsp/rpc.lua:770 "rpc" "...\AppData\Local\nvim-data\mason\bin\phpactor.CMD" "stderr" "PHP Fatal error: Uncaught TypeError: trim(): Argument #1 ($string) must be of type string, false given in phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php:60nStack trace:n#0 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php(60): trim(false)n#1 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php(31): HumbugBox436\KevinGH\RequirementChecker\Terminal::initDimensions()n#2 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Printer.php(28): HumbugBox436\KevinGH\RequirementChecker\Terminal->getWidth()n#3 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Checker.php(17): HumbugBox436\KevinGH\RequirementChecker\Printer->__construct(32, false)n#4 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/bin/check-requirements.php(22): HumbugBox436\KevinGH\RequirementChecker\Checker::checkRequirements()n#5 C:\Users\thadl\AppData\Local\nvim-data\mason\packages\phpactor\phpactor.phar(13): require('phar://C:/Users...')n#6 {main}n thrown in phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php on line 60n"

When I tried using Intelephense, the LSP works for PHP files but fails on blade files. It recognizes the blade file, attaches but doesn’t provide any LSP functionality. I decided to try phpactor but I’m also stuck there.

I’m a novice with neovim, and I’m doing my best with the configurations so it’s possible I’m missing something obvious or doing something wrong.

I essentially want a working PHP LSP for neovim where it works with both PHP files and within .blade.php files. I managed to get the treesitter parser working for blade which took awhile but now I actually need the LSP to work.

Any advice to help me out would be awesome. I’m not sure where to go from here. 🙂 If you need to see anything I haven’t posted, let me know.

laravel -> file_put_contents(/var/www/laravel/storage/framework/views/9f1dc9629406f3376fc417dd6985a806.php): Failed to open stream: Permission denied

docker-compose.yaml

version: "3.8"

services:
  nginx:
    image: "nginx:stable-alpine"
    ports:
      - "8000:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./src:/var/www/laravel
    depends_on:
      - php
      - mysql
  php:
    build:
      context: dockerfiles
      dockerfile: php.Dockerfile
    volumes:
      - ./src:/var/www/laravel
  mysql:
    image: mysql:8.0
    ports:
      - "3316:3306"
    env_file:
      - ./env/mysql.env
  composer:
    build:
      context: dockerfiles
      dockerfile: composer.Dockerfile
    volumes:
      - ./src:/var/www/laravel
  artisan:
    build:
      context: dockerfiles
      dockerfile: php.Dockerfile
    volumes:
      - ./src:/var/www/laravel
    entrypoint: ["php", "/var/www/laravel/artisan"]

php.Dockerfile

FROM php:8.2-fpm-alpine

WORKDIR /var/www/laravel

RUN docker-php-ext-install pdo pdo_mysql

nginx.conf

server {
    listen 80;
    index index.php index.html;
    server_name localhost;
    root /var/www/laravel/public;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ .php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

Error

enter image description here

in the php.dockerfile file I tried to add a line to change access

FROM php:8.2-fpm-alpine

WORKDIR /var/www/laravel

RUN docker-php-ext-install pdo pdo_mysql

RUN chmod -R 777 /var/www/laravel/storage          /*    <------  new line   */

I also tried to change access to the storage folder through WSL

@DESKTOP-VIGTBDU:/src/storage$ sudo chmod -R 777 .

Mail sending failed: stream_socket_enable_crypto(): Peer certificate CN=`98-81-57-227.cprapid.com’ did not match expected CN=`smtp.gmail.com’

Title: “Laravel Email Configuration Not Working on AWS WHM cPanel Server”

Body: “I am using AWS WHM cPanel Shared hosting server to send emails in my Laravel application. Below is my .env configuration for SMTP using Gmail:

Copy code
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
[email protected]
MAIL_PASSWORD="my_password"
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="${APP_NAME}"
MAIL_DEBUG=true

I have tried the following steps with AWS tech support:

Verified that port 587 is open
Double-checked Gmail SMTP settings
Confirmed that MAIL_PASSWORD is correct
However, I still can’t send emails. Could someone suggest a solution?

Issue with Dynamic Input Fields in PHP and JavaScript for Updating Journal Entries [closed]

I am working on a web application that allows users to update journal entries retrieved from a MySQL database. The form for editing these entries includes both static inputs (retrieved from the database) and dynamic inputs (added by the user). However, when I attempt to add a new dynamic input row and submit the form, I receive an error message indicating that an error occurred while processing the data. Specifically, the error is:

“An error occurred while processing the data. Please try again.”

The dynamic inputs do not seem to be recognized when the form is submitted, which prevents the update from being successful.

Problem Breakdown:
Static vs. Dynamic Inputs:

The static inputs (fetched from the database) work correctly.
The dynamic inputs (added using JavaScript) do not get processed correctly, leading to missing values in the $_POST array.
Expected Behavior:

When I click the “Add Row” button, a new row should be appended to the table with fields for the user to fill in (debtor, creditor, description, etc.).
Upon form submission, all values from both static and dynamic inputs should be processed correctly.
Actual Behavior:

Only the values from the static inputs are recognized in the $_POST array.
Dynamic fields return empty values or are not sent at all, resulting in the error message mentioned above.

PHP and JavaScript Code:

$account = $antiXss->xss_clean($_POST["account"]); 
$debtor = $_POST["debtor"]; 
$creditor = $_POST["creditor"]; 
$description = $antiXss->xss_clean($_POST["description"]); 
$acc_serial = $antiXss->xss_clean($_POST["acc_serial"]);
$has_error = false;

foreach ($account as $index => $count) {
if (isset($account[$index]) && isset($debtor[$index]) && isset($creditor[$index]) && isset($description[$index]) && isset($acc_serial[$index])) {
    $s_account = htmlspecialchars(strip_tags($antiXss->xss_clean($account[$index])));
    $s_debtor = filter_var($debtor[$index], FILTER_SANITIZE_NUMBER_INT);
    $s_creditor = filter_var($creditor[$index], FILTER_SANITIZE_NUMBER_INT);
    $s_description = htmlspecialchars(strip_tags($antiXss->xss_clean($description[$index])));
    $s_acc_serial = htmlspecialchars(strip_tags($antiXss->xss_clean($acc_serial[$index])));

    if (empty($s_account) || $s_debtor == "" || $s_creditor == "" || empty($s_description) || empty($s_acc_serial)) {
        echo '<script> $(document).ready(function(){ toastr.error("Please fill in all fields"); }) </script>';
        $has_error = true;
        break;
    }
    if ($s_debtor == $s_creditor) {
        echo '<script> $(document).ready(function(){ toastr.error("Debtor and Creditor cannot be equal in the same row"); }) </script>';
        $has_error = true;
        break;
    }
} else {
    echo '<script> $(document).ready(function(){ toastr.error("An error occurred while processing the data. Please try again."); }) </script>';
    var_dump($_POST["account"], $_POST["debtor"], $_POST["creditor"], $_POST["description"], $_POST["acc_serial"]);
    $has_error = true;
    break;
}
}

**JavaScript for Dynamically Adding Rows:
**

$('#dynamicAddRemove').on('change', '.select_acount', function() {
$(this).closest('tr').find('.acc_serial').val($(this).val()); });
$('#dynamicAddRemove').on('change', '.select_acount', function() {
$(this).closest('tr').find('.mount').val($(this).find("option:selected").text());
});


$(document).ready(function() {
  $('.js-example-basic-single').select2();
});

var dataElement = document.getElementById('data');
var data = JSON.parse(dataElement.dataset.rows);
var product_dd = "";
product_dd += '<select class="form-control select_acount js-example-basic-single select2" name="account[]" required>';
product_dd += '<option value="">--choose account--</option>';
if (Array.isArray(data)) {
data.forEach(function(item) {
  product_dd += '<option value="' + item.acc_serial + '">' + item.acc_name + '</option>';
});
} else {
console.error("Error: Invalid data format");
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr>'+
  '<td class="td">'+product_dd+'</td>'+
  '<td class="td"><input type="text" name="debtor[]" class="form-control debtor" required></td>'+
  '<td class="td"><input type="text" name="creditor[]" class="form-control creditor" required></td>'+
  '<td><input type="text" name="description[]" class="form-control" required></td>'+
  '<td><input type="hidden" name="acc_serial[]" class="form-control acc_serial" required></td>'+
  '<td><button type="button" class="btn btn-danger remove-tr"><i class="fas fa-trash"></i></button></td>'+
  '</tr>');
$('.js-example-basic-single').select2();
});

HTML

<tr>
    <td>
        <select class="form-control select_acount js-example-basic-single select2" name="account[]" required>
            <option value="<?php echo $_acc_serial_token;?>"><?php echo $_account;?></option>
        </select>
    </td>
    <td>
        <input type="text" style="max-width: 94px;" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false" name="debtor[]" value="<?php echo $_debtor;?>" class="form-control debtor" required>
    </td>
    <td>
        <input type="text" style="max-width: 94px;" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false" name="creditor[]" value="<?php echo $_creditor; ?>" class="form-control creditor" required>
    </td>
    <td>
        <input type="text" name="description[]" value="<?php echo $_description; ?>" style="min-width: 205px;" class="form-control" required>
    </td>
    <td>
        <input name="acc_serial[]" class="form-control acc_serial" type="hidden" value="<?php echo $_acc_serial_token; ?>" required>
    </td>
    <td>
        <button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash"></i></button>
    </td>
</tr>
  • I used var_dump($_POST) to check the new inputs after clicking the “Add Row” button. The output showed that the dynamically added inputs weren’t passed in $_POST.
  • I ensured that input names included [] (like debtor[] and creditor[]) to gather them as array fields, but the issue persists.
  • I tried validating the values with JavaScript and PHP to make sure they’re correctly set when adding a new row.

Woo commerce cart is taxing shipping separately not of total order

Woo commerce cart is taxing shipping separately not of total order. Simply I am trying to add 10 percent tax to overall order and its returning the wrong results.

Example : 

item price : $12600
shipping price :$140.98
tax 10% : 1266.90
total Price : $14,007.88

Total Price should amount to $14,015.07 and tax should be
$1274.10.After many tests, the items are taxed
correctly but the shipping is getting tax i think by its self, not 
tax inclusively as total order

Ideally  example results expect:

item 1  : $10
Item 2  : $10 
shipping: $5

Than tax everything at 10%.

Any idea’s?

Tried all combinations within woo commerce setting in regards to shipping and taxes.
Current tax rate set at 10%.

How to Fetch All Users from AD LDAP in Laravel Without Timeout or Memory Issues?

I’m currently working on a Laravel 10 application that integrates with Active Directory (AD) using the AdLdap2 package and PHP’s LDAP functions (PHP 8). However, I’m facing challenges when trying to fetch all users (over 20,000) from the LDAP server.

Here are the two methods I’ve tried:
Method 1: Using AdLdap2 Package

private function handleAdLdapUsersEx($provider): void
{
    try {
        $pageSize = 200;

        if ($this->searchBase->filter) {
            $provider->where($this->searchBase->filter);
        }

        $pagedUsers = $provider->select('distinguishedname', 'givenname', 'name', 'objectguid', 'samaccountname', 'userprincipalname', 'mail')
            ->whereEnabled()
            ->limit($pageSize)
            ->paginate($pageSize, $this->currentPage);
        
        dump($pagedUsers->count());
        
        if ($pagedUsers->count() > 0) {
            collect($pagedUsers->getResults())->chunk(100)->each(function ($chunkedUsers) {
                $this->handleBulk($chunkedUsers);
                unset($chunkedUsers);
                gc_collect_cycles();
            });

            if ($pagedUsers->count() === $pageSize) {
                ImportUsersJob::dispatch($this->searchBase, $this->ldapConnector, $this->ldapConfig, $this->currentPage + 1);
            }
        }
    } catch (Exception $e) {
        dd($e->getMessage());
    }
}

In this method, I set a limit for pagination, even with limit and pagination I am getting all the records in one page, but I’m still experiencing timeouts. Setting public $timeout = 600; works, but I’d like to avoid hardcoding a timeout.

Method 2: Using PHP LDAP Functions

private function handleAdLdapUsers($provider, $ldapConnector): void
{
    try {
        $usersFetched = 0;
        $lastUserEntry = null;

        $ldapConnection = ldap_connect($provider->getConnection()->getHost());
        ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_bind($ldapConnection, $ldapConnector->getUsernames(), $ldapConnector->getPassword());

        $filter = !empty($this->searchBase->filter) ? $this->searchBase->filter : "(objectClass=*)";

        $result = @ldap_search($ldapConnection, $provider->getDn(), $filter, [], 0, 1);
        $firstEntry = ldap_first_entry($ldapConnection, $result);

        while ($firstEntry) {
            $attributes = ldap_get_attributes($ldapConnection, $firstEntry);

            $users = $provider->select('distinguishedname', 'givenname', 'name', 'objectguid', 'samaccountname', 'userprincipalname', 'mail', 'usncreated')
                ->whereEnabled()
                ->get($attributes);

            if ($users->count() > 0) {
                $this->handleBulk($users);
                $usersFetched = $users->count();
            } else {
                break;
            }

            $lastUserEntry = ldap_next_entry($ldapConnection, $firstEntry);
            $firstEntry = $lastUserEntry;
        }

        ldap_unbind($ldapConnection);
    } catch (Exception $e) {
        dd($e->getMessage());
    }
}

This method returns a “Sizelimit exceeded” warning and only fetches 1000 records. I suppressed the warning with @ldap_search, but I still need a way to fetch all users (potentially over 50,000) without hitting size limits or running into memory issues.

  1. How can I modify my queries or pagination to handle fetching all users efficiently?
  2. Are there best practices for dealing with large datasets in Laravel when querying LDAP?
  3. Is there a way to configure the LDAP server to allow fetching more than the default size limit?

Any help or guidance would be greatly appreciated!

How to use sqrt in gmp without loosing data?

I am working with big integer.

I have two equations:

  1. $n = m^4 = “66288484664777839292466735359294353535658376759494957”
  2. x = 4m – 11

To solve it I am using gmp_sqrt (two times)

   $m = gmp_sqrt(gmp_sqrt($n));

After that I am putting value of $m in equation 2. But it is not giving me the desired result because gmp_sqrt is ignoring decimal part. How could I get desired value working in GMP environment?

How to properly configure Livewire in a project? (after unsuccessfully trying to do it)

A few words about the site:

A website made with Laravel 11 is an online e-cigarette store. After I configured the general functionality of the site and the cart, there was a need to make the page not reload every time I click on the cart button, or remove an item from the cart.

The code part (don’t judge too harshly, I wanna to improve myself)

  1. Method index() that works with index.blade.php
    ProductsController:
public function index()
    {
        $cigarettes = Cigarette::all();
        $liquids = Liquid::all();
        $cart = Cart::content();
        $total = Cart::priceTotal(); 

        return view('index', compact('cigarettes', 'liquids','cart', 'total'));
    }

2.A part of the code that is responsible for displaying goods (cigarettes and liquids)

index.blade.php:

<div class="grid">
                    {{-- Cigarettes --}}
                    @forelse($cigarettes as $cigarette)
                        <x-cigarette-card :cigarette="$cigarette"
                                          :cart="$cart"
                        />
                    @empty
                        <div class="#">
                            No cigarettes in the database
                        </div>
                    @endforelse

                    {{-- Liquids --}}
                    @forelse($liquids as $liquid)
                        <x-liquid-card :liquid="$liquid"
                                       :cart="$cart"
                        />

                    @empty
                        <div class="#">
                            No liquids in the database
                        </div>
                    @endforelse
                </div>

(i know that include $cart variable into component with code for product isn’t really fancy, but its my first big project)

3.Code of my components:
components/cigarette-card.blade.php:
@props([‘cigarette’, ‘cart’])

<div class="grid__item">
    <article class="product {{ $cigarette->type }}">
        {{-- Image --}}
        <img class="product__image" src="{{ asset('./storage/' . $cigarette->image) }}" alt="{{ $cigarette->name }}" />

        <div class="product__description">
            {{-- Name --}}
            <h2 class="product__name">{{ $cigarette->name }}</h2>
            {{-- Info --}}
            <div class="product__info">
                ✔&nbsp;Moc - {{ $cigarette->strength }}%
                <br>
                ✔&nbsp;{{ $cigarette->puffs }} zaciÄ…gnięć
                <br>
                ✔&nbsp;Smak: {{ $cigarette->flavor }}
            </div>
            {{-- Price --}}
            <p class="product__price">Cena: {{ $cigarette->price }} zł</p>
        </div>

{{-- Buttons for guests: [Buy] [Delete from cart] [Add to cart] --}}
@guest...@endguest

{{-- Buttons for admins: Admin Panel: [Delete product] [Edit page button] [Show page button] --}}
@auth...@endauth
</article>
</div>

<div>
    {{ $slot }}
</div>

And I’d like to show a form for adding product in cart:
(THIS CODE IS SIMILAR FOR liquids)

components/cigarette-card.blade.php

                {{-- Cart button --}}
                <form action="{{ route('cart.store') }}" method="POST">
                    @csrf

                    {{-- Quantity control --}}
                    <div class="quantity-control">
                        <button type="button" class="quantity-button decrease">-</button>

                        <input type="number" name="quantity" class="quantity-input" 
                        value="1" min="1" readonly/>

                        <button type="button" class="quantity-button increase">+</button>
                    </div>

                    {{-- Product id --}}
                    <input type="hidden" name="product_id" value="{{ $cigarette->id }}">
                    <input type="hidden" name="type" value="cigarette">

                    {{-- Cart button submit (with an image) --}}
                    <button type="submit" 
                     class="button product__button" aria-label="Dodaj do koszyka">

                        <svg class="button__icon" width="20" height="20">
                            <use href="./storage/images/footer-icons/symbol-defs.svg#icon-shopping-cart"></use>
                        </svg>
                    </button>
                </form>

Also I wanna to show a delete from cart form:

                {{-- Delete from cart --}}
                <form action="{{ route('cart.delete') }}" method="POST">
                    @csrf
                    <!-- rowId -->
                    <input type="hidden" name="rowId" value="{{ $cart->where('id', $cigarette->id)->first()->rowId }}">
                    <!-- Product id -->
                    <input type="hidden" name="product_id" value="{{ $cigarette->id }}">
                    <!-- Type -->
                    <input type="hidden" name="type" value="cigarette">

                    <!-- Delete from cart button -->
                    <button type="submit" class="#">Delete from cart</button>
                </form>

Those parts of code (forms are similar for liquids)

What did I try:

First try: After installing Livewire I created two separate components for cigarettes and liquids, then after moving their code to the livewire component I made another livewire component that stored the code for the product (so the cigarette-card and liquid-card code was now in the livewire component, in other words I had a component within a component). After I edited the code in the methods of these components I was still getting page reloads

Second try: After that I decided to do things a bit differently, I made one livewire component, in which I put the code:

<div class="grid">
                    {{-- Cigarettes --}}
                    @forelse($cigarettes as $cigarette)
                        <x-cigarette-card :cigarette="$cigarette"
                                          :cart="$cart"
                        />
                    @empty
                        <div class="#">
                            No cigarettes in the database
                        </div>
                    @endforelse

                    {{-- Liquids --}}
                    @forelse($liquids as $liquid)
                        <x-liquid-card :liquid="$liquid"
                                       :cart="$cart"
                        />

                    @empty
                        <div class="#">
                            No liquids in the database
                        </div>
                    @endforelse
                </div> 

in this component I stopped using the code of cigarette-card and liquid-card components, i.e. now the code that used to be in the components appeared in the livewire component (this added difficulties, because the code became many times more). After reusing the livewire component's livewire method, I was still getting page reloads. 

My opinion:
My theory of what the problem is: maybe the problem lies in the fact that my project uses js code to open and close the cart page, which is a modal window.

Can anyone tell me how can I use Livewire in my project? 

get post from facebook page [closed]

I had a php code which gets the last 3 posts from my Facebook page.
Facebook API Version 15.

Now, version 15 is not available anymore, so I updated my Facebook App (developer portal) to version 21.

This is my code:

// GET FEED
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v21.0/me/feed?'.http_build_query(
    array(
                "limit"   =>   "3",
        "fields"  =>   "attachments,created_time",
        "access_token"  => "XXX"
    )));


$response = json_decode(curl_exec($ch),true);
curl_close($ch);

echo '<pre>';
print_r($response);

Response

Array
(
    [data] => Array
        (
        )
)

Where is my mistake?

I face this issue when I click on the Pay button Moneris Checkout instance not initialized

I try to integrate the Payment Gateway of moneris using PHP and JSon. But When I click on the Pay button It show the error on console sometime it show moerischeckout is not a function sometime it show different error. I try many method but still face the issue. Now I face this error “Moneris Checkout instance not initialized.”

I have tried many method but always show error on the console. I attach code with my question please tell me where I do a mistake.

This is my code,

<?php
require "inc/mpgClasses.php";

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Replace with your Moneris credentials
    $store_id = 'store5'; // Test Store ID
    $api_token = 'yesguy'; // Test API Token
    $token = $_POST['token']; // Token received from Moneris Checkout

    /************************* Transactional Variables ****************************/
    $type = 'purchase';
    $order_id = 'Test' . date("dmy-G:i:s");
    $amount = $_POST['amount']; // Get amount from form
    $pan = $_POST['cardNumber']; // Card number from form
    $expdate = $_POST['expiryDate']; // Expiry date from form
    $crypt = '7'; // Encryption type (for card data)
    $dynamic_descriptor = '123'; // Optional descriptor
    $status_check = 'false'; // For status check; can be set to true if needed

    /*********************** Transactional Associative Array **********************/
    $txnArray = array(
        'type' => $type,
        'order_id' => $order_id,
        'amount' => $amount,
        'pan' => $pan,
        'expdate' => $expdate,
        'crypt_type' => $crypt,
    );

    /**************************** Transaction Object *****************************/
    $mpgTxn = new mpgTransaction($txnArray);

    /****************************** Request Object *******************************/
    $mpgRequest = new mpgRequest($mpgTxn);
    $mpgRequest->setProcCountryCode("CA"); // "US" for sending transaction to US environment
    $mpgRequest->setTestMode(true); // Set to false for production transactions

    /***************************** HTTPS Post Object *****************************/
    $mpgHttpPost = new mpgHttpsPost($store_id, $api_token, $mpgRequest);

    /******************************* Response ************************************/
    $mpgResponse = $mpgHttpPost->getMpgResponse();

    // Process the response
    if ($mpgResponse) {
        echo "<h2>Payment Response:</h2>";
        echo "<p>Card Type: " . $mpgResponse->getCardType() . "</p>";
        echo "<p>Transaction Amount: " . $mpgResponse->getTransAmount() . "</p>";
        echo "<p>Transaction Number: " . $mpgResponse->getTxnNumber() . "</p>";
        echo "<p>Receipt ID: " . $mpgResponse->getReceiptId() . "</p>";
        echo "<p>Transaction Type: " . $mpgResponse->getTransType() . "</p>";
        echo "<p>Reference Number: " . $mpgResponse->getReferenceNum() . "</p>";
        echo "<p>Response Code: " . $mpgResponse->getResponseCode() . "</p>";
        echo "<p>Message: " . $mpgResponse->getMessage() . "</p>";
        echo "<p>Auth Code: " . $mpgResponse->getAuthCode() . "</p>";
        echo "<p>Complete: " . $mpgResponse->getComplete() . "</p>";
    } else {
        echo "<p>Error processing the payment.</p>";
    }
    // Send response data to another server (e.g., your internal logging server)
    $logUrl = 'https://esqa.moneris.com/gateway2/transaction/payment.json'; // Replace with your URL
    $ch = curl_init($logUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
    ]);
    $logResponse = curl_exec($ch);
    curl_close($ch);
    
    // Optionally, handle the logging server response
    // echo "Logging server response: " . $logResponse;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Moneris Payment Integration</title>
    <script src="https://gatewayt.moneris.com/chktv2/js/chkt_v2.00.js"></script>
</head>
<body>

<h2>Moneris Payment Form</h2>
<form id="paymentForm" method="post">
    <label for="amount">Amount:</label>
    <input type="text" id="amount" name="amount" required><br>
    
    <label for="cardNumber">Card Number:</label>
    <input type="text" id="cardNumber" name="cardNumber" required><br>

    <label for="expiryDate">Expiry Date (MMYY):</label>
    <input type="text" id="expiryDate" name="expiryDate" required><br>

    <label for="cvv">CVV:</label>
    <input type="text" id="cvv" name="cvv" required><br>

    <input type="hidden" id="token" name="token">
    <button type="submit">Pay</button>
</form>

<script>
    let monerisCheckoutInstance;

    // Initialize Moneris Checkout on window load
    window.onload = function () {
        window.onbeforeunload = function (e) 
        {
            const storeId = 'store5'; // Test Store ID
            const apiKey = 'yesguy'; // Test API Key

            // Initialize Moneris Checkout
            monerisCheckoutInstance = monerisCheckout({
                checkoutId: apiKey, // Use the API Key as the checkoutId
                environment: 'qa', // Set to 'qa' for testing, use 'prod' for production
            });
        };
    };

    // Handle the form submission
    document.getElementById('paymentForm').onsubmit = function (e) {
        e.preventDefault();

        if (monerisCheckoutInstance) {
            // Tokenize card data
            monerisCheckoutInstance.tokenize({
                card: {
                    pan: document.getElementById('cardNumber').value,
                    expdate: document.getElementById('expiryDate').value,
                    cvv: document.getElementById('cvv').value
                }
            }, function (response) {
                // Handle token response
                if (response && response.token) {
                    // Set the token to the hidden input field
                    document.getElementById('token').value = response.token;
                    // Now submit the form
                    document.getElementById('paymentForm').submit();
                } else {
                    alert('Tokenization failed. Please check the entered card details.');
                }
            }, function (error) {
                console.error('Checkout error:', error);
                alert('Error during payment process. Please check the console for more details.');
            });
        } else {
            console.error('Moneris Checkout instance not initialized.');
        }
    };
</script>

</body>
</html>

Codeigniter 3 flashdata bootstrap message not showing although data added to database

Making a simple codeigniter 3 web application
where i wanted to add category name to the database through a form but even after submit the set flashdata msg not showing on front end..although i can see data added to table in phpmyadmin

here is my code views list.php


<?php $this->load->view('admin/header'); ?>

    <!-- Content Header (Page header) -->
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0 text-dark">Categories</h1>
          </div><!-- /.col -->
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active">Categories</li>
            </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->
 <!-- Main content -->
    <div class="content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-lg-12">
               <?php 
      if($this->session->flashdata('success') !=  ""){ ?>
         <div class='alert alert-success mb-3'><?php echo $this->session->flashdata('success');?></div>;
    <?php  }
       ?>
              
             <!--<div class="alert alert-success">success</div>-->
            <div class="card">
               <!--<div class="card-body d-flex justify-content-center align-items-center" style="height:450px;">
                <h3 class="">Welcome to Codeigniter Web Console</h5>
              </div>-->
              <div class="card-header">
                 <div class="card-title">
                     <form id="SearchFrm" name="searchFrm" action="" method="">
                          <div class="input-group mb-0">
                              <input type="text" value="" class="form-control" placeholder="Search" id="" name="q">
                              <div class="input-group-append">
                                <button class="input-group-text"><i class="fas fa-search"></i></button>
                              </div>
                         </div>
                     </form>
                    
                 </div><!--card-title-->
                 <div class="card-tools">
                     <a href="<?php echo base_url().'admin/category/create' ?>" class="btn btn-primary"><i class="fas fa-plus"></i> Create </a>
                 </div>
              </div><!--card-header-->
              
              <div class="card-body">
                  <table class="table table-striped">
                    <thead>
                      <tr>
                        <th width="50">#</th>
                        <th>Name</th>
                        <th width="100">Status</th>
                        <th width="160" class="text-center">Action</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td>1</td>
                        <td>Fashion</td>
                        <td><span class="badge badge-success">Staus</span></td>
                        <td class="text-center"><a href="" class="btn btn-sm  btn-primary"><i class="fas fa-edit"></i> Edit</a><a href="" class="btn btn-sm btn-danger ml-1"><i class="fas fa-trash-alt"></i> Delete</a></td>
                      </tr>
                      <tr>
                        <td>1</td>
                        <td>Fashion</td>
                        <td><span class="badge badge-success">Staus</span></td>
                        <td class="text-center"><a href="" class="btn btn-sm  btn-primary"><i class="fas fa-edit"></i> Edit</a><a href="" class="btn btn-sm btn-danger ml-1"><i class="fas fa-trash-alt"></i> Delete</a></td>
                      </tr>
                      <tr>
                        <td>1</td>
                        <td>Fashion</td>
                        <td><span class="badge badge-success">Staus</span></td>
                        <td class="text-center"><a href="" class="btn btn-sm  btn-primary"><i class="fas fa-edit"></i> Edit</a><a href="" class="btn btn-sm btn-danger ml-1"><i class="fas fa-trash-alt"></i> Delete</a></td>
                      </tr>
                     
                    </tbody>
                 </table>
              </div><!--card-body-->
              
            </div>
          </div>
          <!-- /.col-md-6 -->
       
        </div>
        <!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->

<?php $this->load->view('admin/footer'); ?>
 

 

i even tried this code

 <?php if($this->session->flashdata('success') != ""){ ?>
             <div class="alert alert-success"><?php echo $this->session->flashdata('success'); ?></div>
             <?php } ?>

but that didnt work too