Is there a way to duplicate all the variations and their values of one product in WooCommerce to all the other products in a given category?

I have over 400 products in my WooComerce store, and they all were done as a simple product. The problem is that now I have to add variations to all the products (to satify a shipping plugin) and it will take me forever if I have to do this manually for each product.

I have setup one of my product with all the variations and values needed to be duplicated to the other products of the same category.

I tried piecing together a simple plugin to do this based on TSCAmerica.com answer.

Below is the complete plugin code for anyone to try out and see if it is working for them or where it needs to be fixed:

<?php

/*
Plugin Name:  WC Copy Variations
Plugin URI:   https://www.example.com
Description:  Copy a Woocommerce Product's Variations From One Product to Another
Version:      1.0
Author:       Wayne Schulz
Author URI:   https://www.example.com
License:      GPL2
License URI:  https://www.gnu.org/licenses/gpl-2.0.html
Text Domain:  wc-copy-variations
Domain Path:  /languages
*/

// plugin settings menu
add_action('admin_menu', 'wcvc_create_menu');

function wcvc_create_menu() {

    //create new top-level menu
    add_menu_page('WC Copy Variations Settings', 'Copy Variations', 'administrator', __FILE__, 'wcvc_settings_page' , plugins_url('/images/icon.png', __FILE__) );

    //call register settings function
    add_action( 'admin_init', 'register_wcvc_settings' );
}


function register_wcvc_settings() {
    //register our settings
    register_setting( 'wcvc-settings-group', 'source_product_id' );
    register_setting( 'wcvc-settings-group', 'target_product_id' );
        register_setting( 'wcvc-settings-group', 'wcvc_status' );
    
}

function wcvc_settings_page() {

// Trigger wcv copy
$wcvc_status = get_option('wcvc_status');
    if(str_contains($wcvc_status, 'yes')) {
        perform_wcv_copy();
    }

?>
<div class="wrap">
<h1>WC Copy Variations</h1>

<form method="post" action="options.php">
    <?php settings_fields( 'wcvc-settings-group' ); ?>
    <?php do_settings_sections( 'wcvc-settings-group' ); ?>
    <table class="form-table">
        <tr valign="top">
        <th scope="row">Source Product ID</th>
        <td><input type="text" name="source_product_id" value="<?php echo esc_attr( get_option('source_product_id') ); ?>" /></td>
        </tr>
         
        <tr valign="top">
        <th scope="row">Target Product ID</th>
        <td><input type="text" name="target_product_id" value="<?php echo esc_attr( get_option('target_product_id') ); ?>" /></td>
        </tr>
        
        <tr valign="top">
        <th scope="row">Type 'yes' to copy</th>
        <td><input type="text" name="wcvc_status" value="<?php echo esc_attr( get_option('wcvc_status') ); ?>" /></td>
        </tr>
    </table>
    <?php submit_button(); ?>
</form>

</div>
<table><tr><td style="vertical-align: top;"><?php show_wcv_source(); ?></td><td style="vertical-align: top;"><?php show_wcv_target(); ?></td></tr></table>

<?php }

function perform_wcv_copy() {
    global $options;
    $source_product_id = get_option('source_product_id');
    $target_product_id = get_option('target_product_id');

    $source_product = wc_get_product($source_product_id);

    // Check if the source product has variations
    if ($source_product->is_type('variable')) {
        // Get the variations of the source product
        $variations = $source_product->get_children();

        foreach ($variations as $variation_id) {
            $variation = wc_get_product($variation_id);

            // Create a new variation for the target product
            $new_variation = new WC_Product_Variation();
            $new_variation->set_parent_id($target_product_id);
            
            // Set attributes and other settings from the source variation
            $new_variation->set_attributes($variation->get_attributes());
            $new_variation->set_regular_price($variation->get_regular_price());
            $new_variation->set_sale_price($variation->get_sale_price());
            $new_variation->set_weight($variation->get_weight());
            $new_variation->set_length($variation->get_length());
            $new_variation->set_height($variation->get_height());
            $new_variation->set_width($variation->get_width());
            
            // Save the new variation
            $new_variation->save();
        }
    }
    update_option( 'wcvc_status', 'done' );
}

function show_wcv_source() {

    global $options;
    $source_product_id = get_option('source_product_id');
    $target_product_id = get_option('target_product_id');
    echo '<p><strong>Source Product ID: '.$source_product_id.'</strong><br />';
    echo 'Product Categories: '.wc_get_product_category_list($source_product_id).'</p>';
    $source_product = wc_get_product($source_product_id);

    // Check if the source product has variations
    if ($source_product->is_type('variable')) {
        // Get the variations of the source product
        $s_variations = $source_product->get_children();
        
        foreach ($s_variations as $s_variation_id) {
            $s_variation = wc_get_product($s_variation_id);
            
            echo '<div class="wrap"><p>';
            
            //$raw_variation = var_export($variation, true);
            //echo 'Variation ID: '.$raw_variation.'<br />';

            echo 'Attributes: ';
            var_dump($s_variation->get_attributes());
            echo '<br />';
            
            $s_regular_price = $s_variation->get_regular_price();
            echo 'Regular Price: '.$s_regular_price.'<br />';

            $s_sale_price = $s_variation->get_sale_price();
            echo 'Sale Price: '.$s_sale_price.'<br />';
            
            $s_weight = $s_variation->get_weight();
            echo 'Weight: '.$s_weight.'<br />';
            
            $s_length = $s_variation->get_length();
            echo 'Length: '.$s_length.'<br />';
            
            $s_height = $s_variation->get_height();
            echo 'Height: '.$s_height.'<br />';
            
            $s_width = $s_variation->get_width();
            echo 'Width: '.$s_width.'<br />';
            
            echo '</p></div>';
        }
    }
}

function show_wcv_target() {

    global $options;
    $source_product_id = get_option('source_product_id');
    $target_product_id = get_option('target_product_id');
    echo '<p><strong>Target Product ID: '.$target_product_id.'</strong><br />';
    echo 'Product Categories: '.wc_get_product_category_list($target_product_id).'</p>';
    $target_product = wc_get_product($target_product_id);

    // Check if the target product has variations
    if ($target_product->is_type('variable')) {
        // Get the variations of the target product (if any)
        $variations = $target_product->get_children();
        
        foreach ($t_variations as $t_variation_id) {
            $t_variation = wc_get_product($t_variation_id);
            
            echo '<div class="wrap"><p>';
            
            // $raw_variation = var_export($variation, true);
            // echo 'Variation ID: '.$raw_variation.'<br />';

            echo 'Attributes: ';
            var_dump($t_variation->get_attributes());
            echo '<br />';
            
            $t_regular_price = $t_variation->get_regular_price();
            echo 'Regular Price: '.$t_regular_price.'<br />';

            $t_sale_price = $t_variation->get_sale_price();
            echo 'Sale Price: '.$t_sale_price.'<br />';
            
            $t_weight = $t_variation->get_weight();
            echo 'Weight: '.$t_weight.'<br />';
            
            $t_length = $t_variation->get_length();
            echo 'Length: '.$t_length.'<br />';
            
            $t_height = $t_variation->get_height();
            echo 'Height: '.$t_height.'<br />';
            
            $t_width = $t_variation->get_width();
            echo 'Width: '.$t_width.'<br />';
            
            echo '</p></div>';
        }
    }
}

?>

Enter the source ID and the target ID and hit save, then it will dispaly any variations in the source and target products. If you want to perform the copy, enter ‘yes’ in the last field and hit save again.

The issue I am having is that it is not saving the new variations to the target product. I VAR DUMPED every possible variable and the data is there in the right places. After the save command, the ID does increment for each new variation, however, either the save() is not working properly for some reason or WooComerce is deleting the saved variation immediately after the save.

What am I missing or doing wrong?

Avoid php malicious code hidden in uploaded image files? [duplicate]

I have created a PHP class which I use to resize uploaded images.
The class checks the extension of the file and accordingly calls the proper function to start editing the image, like imagecreatefromjpeg, imagecreatefrompng, and so on…

I read that it is possible to embed malicious code in the EXIF data or other part of an image.

So how can I optimize my code and make it more secure in order to prevent that a compromised image file can run malicious code?
Is there a better way to detect the file type other that checking at its extension?

I already checked the answers given to another question (Malicious Code Through Image Upload), but it doesn’t tackle all my doubts.

A more robust code would help everyone handling uploaded images with PHP.

The workflow I am using is basically this for a JPEG file:

$uploaded_file = 'uploaded/image.jpg';
$destination_file_url = 'uploaded/image_resized.jpg';
$extension = strtolower(strrchr($uploaded_file, '.'));

.....

if (getimagesize($uploaded_file) === false) {
   die("This is not an image!");
}

$newImage = imagecreatetruecolor($newWidth, $newHeight);
$image = imagecreatefromjpeg($uploaded_file);

imagecopyresampled($newImage, $image, $cropStartX, $cropStartY, 0, 0, $optimalWidth, $optimalHeight, $original_width, $original_height);

$exif = @exif_read_data($uploaded_file);
.....

imageinterlace($newImage, 1);
imagejpeg($newImage, $destination_file, 90);

imagedestroy($image);
imagedestroy($newImage);

Thanks a lot for your help!

How to Generate Unique IDs for Chat Messages in Laravel with GridDB?

I’m building a real-time chat application using Laravel and want to use GridDB as my database due to its high performance with time-series data. Since GridDB doesn’t have an official PHP client, I’ve set up a custom integration using a middleware API in Python that communicates with GridDB. My Laravel application interacts with this middleware via HTTP requests.

In my chat application, each message needs a unique ID. In traditional relational databases like MySQL, I would use an auto-incrementing integer as the primary key. Since GridDB doesn’t support auto-incrementing IDs natively, I need a reliable way to generate unique IDs for chat messages that can handle high concurrency since multiple users might send messages simultaneously.

I tried combining the current timestamp with a random number:

$messageId = time() . mt_rand(1000, 9999);

This reduces the chance of collisions but isn’t foolproof, especially under high load.

I attempted to simulate auto-increment by querying the maximum existing ID and incrementing it:

$maxId = $this->getMaxMessageIdFromGridDB();
$messageId = $maxId + 1;

However, this approach isn’t safe in a concurrent environment and can lead to race conditions.

Would using GridDB’s TIMESTAMP row key with sub-second precision be a viable option for unique IDs?

Laravel Eloquent Query Running So SLOWLY as compared to mySQL counterpart

Why is this laravel eloquent query running so SLOWLY?

I have a query running in a Laravel job that executes very slowly and inconsistently. Sometimes it takes 1-2 minutes to fetch the result, while at other times it completes in just 1-2 seconds for the same exact query.

Slow Full Eloquent Query ( Takes 1-2 minutes for the query to be completed )

$relevantRobot = AppRobot::where('serial_number', 'TEST-ID')
                    ->whereHas('robot_maps', function($query) use ($robot_map_name) {
                        $query->where('name', $robot_map_name);
                    })
                    ->with(['robot_maps' => function($query) use ($robot_map_name) {
                            $query->where('name', $robot_map_name);
                        },
                        'current_robot_position',
                        'current_robot_position.robot_map',
                        'latest_robot_deployment_information_request'
                    ])
                    ->first(); // Get the raw SQL query

Slow Reduced Eloquent Query ( Takes 1-2 minutes for the query to be completed )

$relevantRobot = AppRobot::where('serial_number', 'TEST-ID')
                    ->whereHas('robot_maps', function($query) use ($robot_map_name) {
                        $query->where('name', $robot_map_name);
                    })
                    ->with(
                        'current_robot_position',
                    ])
                    ->first(); // Get the raw SQL query

Fast Reduced Eloquent Query ( Completes in less than a second )

$relevantRobot = AppRobot::where('serial_number', 'TEST-ID')
                    ->whereHas('robot_maps', function($query) use ($robot_map_name) {
                        $query->where('name', $robot_map_name);
                    })
                    ->with(
                        'latest_robot_deployment_information_request',
                    ])
                    ->first(); // Get the raw SQL query

SQL Query ( Completes in less than a second )

select * from `robots` where `serial_number` = 'TEST-ID' and exists (select * from `robot_maps` where `robots`.`id` = `robot_maps`.`robot_id` and `name` = 'test' and `active` = 1);

Eloquent Relationship

 public function current_robot_position(){
        return $this->hasOne('AppRobotMapPositionLog','robot_id','id')
            ->orderBy('id','desc');
    }

Attempted Solution

After noticing the slow load time when eagerly loading current_robot_position, I added indexes to the columns used in that relationship (id). However, this hasn’t improved the performance.

I also tried converting the Eloquent query to a raw MySQL query using toSql(), and it ran extremely fast (under 1 second).

What is wrong? What am I missing?

Trying to delete row from database with JS and PHP not working [duplicate]

I got this main PHP file (index.php), its has an html button with an int value and onclick it calls a JS function on the same file.

The JS function receives the value of the button and should send a POST request to another PHP file with the button’s value.

Then the PHP should execute another function.

Finally it comes back to the first html/JS file. I don’t know if it isn’t sending the request or what.

Button (index.php):
<input name="delete" class="imageButton" id="deleteButton" type="submit" value="<?php echo "{$id}";?>" onclick="pr()">

JS Function (index.php):

function pr() {
  if (confirm("¿Borrar contacto con id: " + document.getElementById("deleteButton").value  + "?")) {
    jQuery.ajax({
      url: "./Utils/DeleteContact.php",
      type: "POST",
      data: {"deleteContact": document.getElementById("deleteButton").value}
    });
    window.location.href = "./Utils/DeleteContact.php";
  }
}

DeleteContact.php:

<?php
    //TODO
    if (isset($_POST["deleteContact"])) {
        deleteContact($_POST["deleteContact"]);
        header("../index.php");
    }

    function deleteContact(int $id) {
        $delete = "delete from registros where id = {$id}";

        try {
            mysqli_query($_SESSION["connection"], $delete);
        } catch (mysqli_sql_exception) {
            echo '<p style="color: red;">Error al borrar contacto</p>';
        }
    }
?>

don’t know much of JS yet, tried using JQuery.post, get, ajax, using a variable for the ajax data and replacint JQuery. for $.

How to Integrate GridDB with Laravel Using a Custom Database Driver?

I’m working on a Laravel project where I want to use GridDB as my database. Since Laravel doesn’t have built-in support for GridDB, I’m trying to create a custom database driver to handle the connection, since there’s a connector for PHP in their docs. Here’s what I’ve done so far:

  1. Created a custom database driver:

'connections' => [ // Other connections...

'griddb' => [
'driver' => 'griddb',
'host' => env('GRIDDB_HOST', '127.0.0.1'),
'port' => env('GRIDDB_PORT', 10001),
'cluster' => env('GRIDDB_CLUSTER', 'myCluster'),
'username' => env('GRIDDB_USERNAME', 'admin'),
'password' => env('GRIDDB_PASSWORD', 'admin'),
],
],
  1. Created a service provider for it:
class GridDBServiceProvider extends ServiceProvider
{
public function register()
{
$this->app['db']->extend('griddb', function ($config, $name) {
$config['name'] = $name;
return new GridDBConnection($config);
});
}
}
  1. Added the Connection class:
class GridDBConnection extends Connection
{
protected $gridstore;



public function __construct(array $config)
{
$factory = StoreFactory::getInstance();
$this->gridstore = $factory->getStore([
'notificationMember' => $config['host'] . ':' . $config['port'],
'clusterName' => $config['cluster'],
'user' => $config['username'],
'password' => $config['password'],
]);



parent::__construct($this->gridstore);
}
}

  1. Added the service provider:
'providers' => [
// providers ..
AppProvidersGridDBServiceProvider::class,
]

So when I try to run migrations I get

unsupported driver [griddb].

Does anyone know what is happening, why is the connector not connecting?

Why use a different server to execute a force download script? [closed]

I m working on a project which uses an API to fetch URL of a video or audio, I want users to able to download the video/audio and for that I wrote script to force download the file. Everything is working correctly, but I recently discovered that other similar tools/apps uses a different host/domain to run the force download script.
for example, if their website is

www.abc.com

, the download link will be something like

dl.something.com/download?token=

the problem is I do not know how to achieve this corretly, if my website is

www.123.com

, force downloading script can be executed by

www.123.com/download?token=

so my questions are –

  1. Why others are using different server to host force download script ?
  2. What will be the correct way to achieve this, without using database, how session variables can be passed to a different host ?
  3. does it affect bandwidth ?

Apologies if I did not clarify everything correctly or if the questions are not correct, but m a beginner and couldn’t find answer to this anywhere

Fatal error: apply_filters() conflict in email Customizer plugin

I use a plugin Woocommerce Email Customizer but recently the email refused to work giving PHP Error email cannot display

  1. ***/public_html/wp-content/plugins/woocommerce-email-control/ec-email-control.php(1059): apply_filters()

  2. ***/public_html/wp-content/plugins/woocommerce-email-control/ec-email-control.php(1005): WC_Email_Control->ec_style_inline_for_old_wc()

  3. ***/public_html/wp-content/plugins/woocommerce-email-control/pages/ec-preview-page.php(195): apply_filters()

  4. **/public_html/wp-content/plugins/woocommerce-email-control/ec-email-control.php(562): require_once(‘//*/…’)

How do I tackle this and what does this error mean

There’s no more support for this plugin or update as developer is gone!

I have tried to rewrite the hook function but it just seems I’m not getting it

Twillo Object Printing difference between localhost and live server

require_once 'vendor/autoload.php';
use TwilioRestClient;

$sid    = "ACe39b1abc88826a6a4b571e0d0c829d25";
$token  = "579fd6e6fdb99ccdbd4db57d54e23ad6";
$twilio = new Client($sid, $token);

$verification_check = $twilio->verify->v2->services("VA60737f4811c8c00f6a9a5297962c2b3f")
                                   ->verificationChecks
                                   ->create([
                                                "to" => "+911234567890",
                                                "code" => "888577"
                                            ]
                                    );
print($verification_check);
print($verification_check->status);

the same code prints the whole object on localhost but prints [Twilio.Verify.V2.VerificationCheckInstance] like this on live worpress server . but I can access the properties like print($verification_check->status); on both local and live . Another point to mention I downloaded the twillo from composer on localhost and uploaded the directory to wordpress theme folder

Jazz Cash – API intergration ERROR – “Provided Transaction Type and Version are not allowed”

JazzCash Payment Integration Error: Transaction Type and Version Not Allowed

Problem

I’m trying to integrate JazzCash payment gateway in PHP but getting an error response saying “Provided Transaction Type and Version are not allowed”. I’m using their sandbox environment for testing.

Code

Here’s my PHP class for JazzCash integration:

class JazzCashPayment {
    private $merchantId;
    private $password;
    private $integritySalt;
    private $apiUrl;

    public function __construct($merchantId, $password, $integritySalt, $isProduction = false) {
        $this->merchantId = $merchantId;
        $this->password = $password;
        $this->integritySalt = $integritySalt;
        $this->apiUrl = $isProduction
            ? 'https://payments.jazzcash.com.pk/ApplicationAPI/API/2.0/Purchase/DoMWalletTransaction'
            : 'https://sandbox.jazzcash.com.pk/ApplicationAPI/API/2.0/Purchase/DoMWalletTransaction';
    }

    public function initializePayment($amount, $mobileNumber, $cnic) {
        date_default_timezone_set('Asia/Karachi');

        $DateTime = new DateTime();
        $dateTime = $DateTime->format('YmdHis');
        //------------------------------------------------------

        //------------------------------------------------------
        //expiry date, add 1 hour to $DateTime
        $ExpiryDateTime = $DateTime;
        $ExpiryDateTime->modify('+' . 1 . ' day');
        $expiryDateTime = $ExpiryDateTime->format('YmdHis');
        //------------------------------------------------------

        $txnRefNo = 'Sol' . $dateTime;
        // $amount = 100 * $amount;
        // Create data array with exact structure and order
        $data = array(
            "pp_CNIC" => $cnic,
            "pp_MobileNumber" => $mobileNumber,
            "pp_Language" => "EN",
            "pp_MerchantID" => $this->merchantId,
            "pp_Password" => $this->password,
            "pp_BankID" => "",
            "pp_ProductID" => "",
            "pp_TxnRefNo" => $txnRefNo,
            "pp_Amount" => $amount,
            "pp_TxnCurrency" => "PKR",
            "pp_TxnDateTime" => $dateTime,
            "pp_BillReference" => "billRef3781",
            "pp_Description" => "Test case description",
            "pp_TxnExpiryDateTime" => $expiryDateTime,  // Can be modified for different expiry
            "pp_SecureHash" => "",
            "ppmpf_1" => $mobileNumber,
            "ppmpf_2" => "",
            "ppmpf_3" => "",
            "ppmpf_4" => "",
            "ppmpf_5" => ""
        );

        // Generate and add secure hash
        $data['pp_SecureHash'] = $this->generateSecureHash($data);

        echo '<pre>';
        print_r($data);
        echo '</pre>';
        return $this->makeApiRequest($data);
    }

    public function generateSecureHash($data) {
        // Step 1: Collect only pp-prefixed fields, excluding pp_SecureHash, pp_TxnType, and pp_Version
        $ppData = [];
        foreach ($data as $key => $value) {
            $lowerKey = strtolower($key);
            if (strpos($lowerKey, 'pp') === 0 && $lowerKey !== 'pp_securehash' && $lowerKey !== 'pp_txntype' && $lowerKey !== 'pp_version') {
                $ppData[$lowerKey] = $value;
            }
        }

        // Step 2: Sort fields by ASCII alphabetical order of keys
        ksort($ppData);

        // Step 3: Build the hash string by concatenating values with `&` separator
        $hashString = '';
        foreach ($ppData as $key => $value) {
            if ($value !== "") {  // Only non-empty values
                $hashString .= ($hashString ? '&' : '') . $value;
            }
        }

        // Step 4: Prepend Integrity Salt
        $finalHashString = $this->integritySalt . '&' . $hashString;

        // Step 5: Generate the HMAC hash with SHA-256
        return strtoupper(hash_hmac('sha256', $finalHashString, $this->integritySalt));
    }

    /**
     * Debug method to verify hash generation
     */
    public function debugHash($data) {
        echo "Input Data:n";
        print_r($data);

        // Remove pp_SecureHash
        $ppData = $data;
        unset($ppData['pp_SecureHash']);

        // Sort by keys
        ksort($ppData);

        echo "nSorted Data:n";
        print_r($ppData);

        // Create hash string
        $str = '';
        foreach ($ppData as $value) {
            if ($value !== "") {
                $str = $str . '&' . $value;
            }
        }

        // Add integrity salt
        $str = $this->integritySalt . $str;

        echo "nHash String:n$strn";

        // Generate hash
        $hash = strtoupper(hash_hmac('sha256', $str, $this->integritySalt));
        echo "nGenerated Hash:n$hashn";

        return $hash;
    }

    private function makeApiRequest($data) {
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json'
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            throw new Exception("cURL Error: " . $err);
        }

        return json_decode($response, true);
    }
}

Usage

$jazzcash = new JazzCashPayment(
'XXXX',          // Merchant ID
'XXXXX',       // Password
'XXXX',    // Integrity Salt
false               // Use sandbox environment
);

$response = $jazzcash->initializePayment(
'100',           // Amount
'03123456789',   // Mobile Number
'345678'         // CNIC
);

Error Response

Array(
[pp_ResponseCode] => 110
[pp_ResponseMessage] => Provided Transaction Type and Version are not allowed.
// ... other response fields
)

What I’ve Tried

  • Verified all required fields are being sent
  • Double-checked the secure hash generation
  • Confirmed the API endpoint URL is correct
  • Verified merchant credentials

Question

Looking at the error message, it seems I’m missing the transaction type and version in the request. However, I couldn’t find clear documentation about how to include these parameters. Has anyone successfully integrated JazzCash payments who can point out what I’m missing?

Expected Behavior

The payment should be initialized successfully with the provided parameters.

Additional Context

  • Using PHP 7.4+
  • Testing in sandbox environment
  • Following JazzCash API v2.0`

Database connection with laravel application hosted on hostinger server sub domain [duplicate]

i have Hostinger server when i upload any laravel application on it and connect it with correct database credentials in env it shows
SQLSTATE[HY000] [1045] Access denied for user ‘u334339390_POLydooRdBUsr’@’127.0.0.1’ (using password: YES) (SQL: select * from sessions where id = 26DRGziVVIM0Z9Nn8F0tK8S3sd0FmrrEipRXwOSK limit 1)
but when i connect it with other existing database of existing other laravel application it connect successfully why for new it shows this
please give me its reasons and possible solutions

Document ID is not capturing in form using dropzone library

I am using form and dropzone library to upload document and I was doing testing whether my document ID is capturing or not. Its not capturing and when I check and see the issue is my form dropzone library is preventing it and I am not sure why. I will appreciate any help to identify the issue

This is my code

var tblCandidateDocumentList = $('#tblCandidateDocumentList').DataTable({
        ajax: {
            "url": "action/fn_espdb_getData.php?mod=candidateDocumentList",
            "dataSrc": "candidateDocumentList"
        },
        columns: [
            { data: null },
            {data: null},
            { data: 'document_type_name' },
            {
              data: null,
                render: function (data, type, row) {
                    return `
                      <div class="col-12">
                        <div class="card">
                          <div class="card-body">
                            <form action="/upload" class="dropzone dropZoneCandidate needsclick" data-doc-id="${row.document_id}" id="dropzone-multi-${row.document_id}">
                              <input type="hidden" id="documentTypeID" name="documentTypeID" value="${row.document_id}" class="form-control" readonly>
                              <div class="dz-message needsclick">
                                Drop files here or click to upload
                              </div>
                              <div class="fallback">
                               <input id="file_${row.document_id}" name="file_${row.document_id}" type="file" multiple/>
                              </div>
                            </form>
                          </div>
                        </div>
                      </div> 
                  `;
                }
            },
        ],
        columnDefs: [
          {
            // For Checkboxes
            targets: 0,
            searchable: false,
            orderable: false,
            render: function () {
              return '<input type="checkbox" class="dt-checkboxes form-check-input">';
            },
            checkboxes: {
              selectRow: true,
              selectAllRender: '<input type="checkbox" class="form-check-input">'
            }
          },
        ],
        order: [[1, 'desc']],
        dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 d-flex justify-content-center justify-content-md-end mt-n6 mt-md-0"f>><"table-responsive"t><"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
        language: {
            paginate: {
                next: '<i class="bx bx-chevron-right bx-18px"></i>',
                previous: '<i class="bx bx-chevron-left bx-18px"></i>'
            }
        },
        select: {
            style: 'multi'
        }
    });

This is my backend code

case “addCandidateDetails”:

    // Collect form data
    $candidateID = $_POST['candidateID'] > 0 ? $_POST['candidateID'] : NULL;
    $candidateName = $_POST['candidateName'] == "" ? NULL : $_POST['candidateName'];
    $candidateNationality = $_POST['candidateNationality'] == "" ? NULL : $_POST['candidateNationality'];
    $candidateGender = $_POST['candidateGender'] == "" ? NULL : $_POST['candidateGender'];
    $candidateMaritalStatus = $_POST['candidateMaritalStatus'] == "" ? NULL : $_POST['candidateMaritalStatus'];
    $candidateDOB = $_POST['candidateDOB'] == "" ? NULL : $_POST['candidateDOB'];
    $candidateAge = $_POST['candidateAge'] == "" ? NULL : $_POST['candidateAge'];
    $candidateEmail = $_POST['candidateEmail'] == "" ? NULL : $_POST['candidateEmail'];
    $candidateCompany = $_POST['candidateCompany'] == "" ? NULL : $_POST['candidateCompany'];
    $candidatePassportNo = $_POST['candidatePassportNo'] == "" ? NULL : $_POST['candidatePassportNo'];
    $candidatePassportIssueDate = $_POST['candidatePassportIssueDate'] == "" ? NULL : $_POST['candidatePassportIssueDate'];
    $candidatePassportExpiryDate = $_POST['candidatePassportExpiryDate'] == "" ? NULL : $_POST['candidatePassportExpiryDate'];
    $candidatePlaceOfIssue = $_POST['candidatePlaceOfIssue'] == "" ? NULL : $_POST['candidatePlaceOfIssue'];
    $inMalaysia = $_POST['inMalaysia'] == "" ? NULL : $_POST['inMalaysia'];
    $visaCollectionCenter = $_POST['visaCollectionCenter'] == "" ? NULL : $_POST['visaCollectionCenter'];
    $candidatePermitType = $_POST['candidatePermitType'] == "" ? NULL : $_POST['candidatePermitType'];
    
    // Additional data for tbl_candidate_documents
    $documentTypeID = $_POST['documentTypeID'] == "" ? NULL : $_POST['documentTypeID'];

    // File upload handling
    $uploadDirectory = '/uploads/candidate_files/';
    $uploadedFilePath = NULL;

    echo "Candidate Name : " . $candidateName . "<br>";
    echo "candidate Nationality : " . $candidateNationality . "<br>";
    echo "Candidate Permit Type : " . $candidatePermitType . "<br>";
    echo "Candidate Document ID : " . $documentTypeID . "<br>";
    exit();



    
    
    if (isset($_FILES['candidateFile']) && $_FILES['candidateFile']['error'] == UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['candidateFile']['tmp_name'];
        $fileName = $_FILES['candidateFile']['name'];
        $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);

        // Sanitize candidate name and passport number for the filename
        $sanitizedCandidateName = preg_replace("/[^a-zA-Z0-9]/", "_", $candidateName);
        $sanitizedPassportNo = preg_replace("/[^a-zA-Z0-9]/", "_", $candidatePassportNo);

        // Construct the new file name
        $newFileName = "{$sanitizedCandidateName}_{$sanitizedPassportNo}_Document.{$fileExtension}";
        $uploadedFilePath = $uploadDirectory . $newFileName;

        // Move file to the destination
        if (move_uploaded_file($fileTmpPath, $_SERVER['DOCUMENT_ROOT'] . $uploadedFilePath)) {
            // Insert file details into tbl_candidate_documents
            DB::insert('tbl_candidate_documents', [
                'candidate_id' => $candidateID,
                'document_type_id' => $documentTypeID,
                'permit_id' => $candidatePermitType,
                'document_name' => $newFileName,
                'document_path' => $uploadedFilePath,
                'status' => 1,
                'entry_user' => $username,
                'entry_date' => DB::sqlEval('NOW()')
            ]);
        } else {
            die('Error uploading file.');
        }
    }

    // Insert candidate details into tbl_candidate
    DB::insert('tbl_candidate', [
        'candidate_id' => $candidateID,
        'candidate_name' => $candidateName,
        'candidate_nationality' => $candidateNationality,
        'candidate_gender' => $candidateGender,
        'candidate_dob' => $candidateDOB,
        'candidate_age' => $candidateAge,
        'candidate_email' => $candidateEmail,
        'candidate_customer' => $candidateCompany,
        'candidate_passport_no' => $candidatePassportNo,
        'passport_issue_date' => $candidatePassportIssueDate,
        'passport_expiry_date' => $candidatePassportExpiryDate,
        'candidate_issue_place' => $candidatePlaceOfIssue,
        'candidate_is_in_malaysia' => $inMalaysia,
        'candidate_visa_collection_center' => $visaCollectionCenter,
        'candidate_permit_type_id' => $candidatePermitType,
        'status' => 1,
        'entry_user' => $username,
        'entry_date' => DB::sqlEval('NOW()')
    ]);

    break;

I am encountering an issue with receiving a null value for the Postman bearer token in a Laravel middleware

I am currently experiencing an issue with my Laravel API on a cPanel-hosted environment. When making API requests from Postman with a Bearer token in the Authorization header, the token is not being received by the application. This setup works as expected on my local environment, where the Bearer token is successfully passed and retrieved by the application. However, in the cPanel environment, the Authorization header appears to be missing or stripped out.

I have already tried the following troubleshooting steps:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With"
</IfModule>

I am getting a null value when trying to retrieve the Bearer token using $request->bearerToken() in middleware.

I am using cPanel for my hosting environment.

MouseEnter and MouseLeave target multiple elements on local host

I am developing a website in Kirby environment and I have been testing it on localhost. A function within this website creates a highlight for each .main element that acquires a color upon hovering and changes back upon mouse leaving.

I have encountered a very specific problem that occures upon mouse hovering. The problem overall is that I am trying to target one element, however upon howering the mouse it fires them all at the same time.

I have console logged the function and it seems like that the code indeed detects multiple .main elements being selected.

The function works as intended when I run it on HTML directly from Visual Studio Code. (The screenshot attached is from that version.)

What could be the issue?

<?php foreach ($page->articles()->toStructure() as $article): ?>
                <div class="main">
                  <div class="container" onclick="toggleSibling(this);">
                      <div class="Title"><?= $article->title() ?></div>
                      <div class="Genre"><?= $article->genre() ?></div>
                      <div class="Publisher"><?= $article->publisher() ?></div>
                      <div class="Datum"><?= $article->datum() ?></div>
                  </div>
                  <div class="content">
                                            <div class="Info">
                      <?= $article->info()->kt() ?>
                  </div>
                      <div class="Image">
                          <!-- <img src="content/test/painting-forest-lake.jpg"> -->
                          <div class="swiper">
                              <div class="swiper-wrapper">
                                  <?php foreach ($article->images()->toFiles() as $image): ?>
                                      <div class="swiper-slide">
                                          <img src="<?= $image->url() ?>" alt="<?= $image->alt() ?>">
                                      </div>
                                  <?php endforeach; ?>
                              </div>
                              <div class="swiper-scrollbar"></div>
                              <button class="slick-prev"></button>
                              <button class="slick-next"></button>
                          </div>
                      </div>
                      <div class="Page"></div>
                      <div class="Text">
                          <?= $article->text()->kt() ?>
                      </div>
              </div>
          <?php endforeach; ?>
document.addEventListener('DOMContentLoaded', () => {
  const mainElements = document.querySelectorAll('.main');
  const headerDivs = document.querySelectorAll('.container_header > div');

  const generateLightColor = () => {
    const randomValue = () => Math.floor(Math.random() * 156 + 100);
    return `rgb(${randomValue()}, ${randomValue()}, ${randomValue()})`;
  };

  mainElements.forEach(main => {
    const randomColor = generateLightColor();
    const container = main.querySelector('.container');
    const spans = main.querySelectorAll('span');

    console.log("Generated random color:", randomColor); 

    main.addEventListener('mouseenter', () => {
      container.style.backgroundColor = randomColor;
      document.documentElement.style.setProperty('--color-variable', randomColor);

      headerDivs.forEach(div => {
        div.style.backgroundColor = randomColor;
        div.style.color = container.style.color = 'black';
      });

      spans.forEach(span => {
        span.style.backgroundColor = randomColor;
        span.style.color = 'black';
      });

      console.log("Mouse entered main element:", main); 
    });

    main.addEventListener('mouseleave', () => {
      container.style.backgroundColor = 'var(--color-border-dark)';
      headerDivs.forEach(div => {
        div.style.backgroundColor = 'var(--color-border-dark)';
        div.style.color = container.style.color = 'var(--default-text-color)';
      });

      spans.forEach(span => {
        span.style.backgroundColor = 'transparent';
        span.style.color = 'inherit';
      });

      console.log("Mouse left main element:", main); 
    });
  });
});

I have tried multiple takes, but none of them lead to resloving the problem. A lead I got was it might have to do with dynamic content generation and duplicates.