Issue with Custom Guzzle Client in authenticationClient for SellingPartnerApi::seller()

I’m encountering an issue when passing a custom GuzzleHttpClient instance as the authenticationClient parameter in SellingPartnerApi::seller(). According to the documentation, this parameter should accept a GuzzleHttpClient, but when provided, it results in the following error:

Error:

Typed property SaloonHttpSendersGuzzleSender::$client must not be accessed before initialization.

Steps to Reproduce
Instantiate a GuzzleHttpClient with a proxy

$httpClient = new GuzzleHttpClient([
    'proxy' => 'http://username:password@proxy_host:port',
    'timeout' => 30,
    'connect_timeout' => 30,
]);
// or just an empty client
$httpClient = new GuzzleHttpClient();

Pass it to SellingPartnerApi::seller()

$api = SellingPartnerApi::seller(
    clientId: $credentials->api_client_id,
    clientSecret: $credentials->api_client_secret,
    refreshToken: $credentials->refresh_token,
    endpoint: Endpoint::NA,
    authenticationClient: $httpClient
);

Attempt to make a request:

$response = $api->sellersV1()->getMarketplaceParticipations();

Additional Information

  • PHP: 8.4.1
  • Selling Partner API SDK: 7.2.4 (jlevers/selling-partner-api)
  • Guzzle: 7.9.2
  • Laravel: 11.41.3

I’ve confirmed that the issue persists even when using a clean GuzzleHttpClient instance without additional configuration.

Is there an internal constraint preventing the use of a custom GuzzleHttpClient, or is there a required initialization step that is missing? Any guidance would be appreciated.

Laravel sail thrown error about nginx sll

I faced with error

zipsure-20-nginx-1          "/docker-entrypoint.…"   nginx               exited (1) 

when executed ./vendor/bin/sail up -d --build
Before clear all docker stuff, executed

docker system prune -a --volumes
docker rm -vf $(docker ps -a -q)

composer json

"laravel/sail": "^1.19",
"laravel/framework": "^8.0",
"ryoluo/sail-ssl": "^1.2" 

was installed ryoluo/sail-ssl 1.3.2 in composer lock

error

zipsure-20-nginx-1  | Error checking extensions defined using -addext
zipsure-20-nginx-1  | 4037D3CDE27A0000:error:1100006C:X509 V3 routines:X509V3_parse_list:invalid empty name:../crypto/x509/v3_utl.c:389:
zipsure-20-nginx-1  | 4037D3CDE27A0000:error:11000069:X509 V3 routines:do_ext_nconf:invalid extension string:../crypto/x509/v3_conf.c:102:name=subjectAltName,section=
zipsure-20-nginx-1  | 4037D3CDE27A0000:error:11000080:X509 V3 routines:X509V3_EXT_nconf_int:error in extension:../crypto/x509/v3_conf.c:48:section=default, name=subjectAltName, value=
zipsure-20-nginx-1  | 99-generate-ssl-cert.sh: Server certificate has been generated.
zipsure-20-nginx-1  | /docker-entrypoint.sh: Configuration complete; ready for start up
zipsure-20-nginx-1  | 2025/01/30 10:02:44 [emerg] 1#1: cannot load certificate "/etc/nginx/certs/server.pem": BIO_new_file() failed (SSL: error:80000002:system library::No such file or directory:calling fopen(/etc/nginx/certs/server.pem, r) error:10000080:BIO routines::no such file)
zipsure-20-nginx-1  | nginx: [emerg] cannot load certificate "/etc/nginx/certs/server.pem": BIO_new_file() failed (SSL: error:80000002:system library::No such file or directory:calling fopen(/etc/nginx/certs/server.pem, r) error:10000080:BIO routines::no such file)

docker-compose.yml

services:
    nginx:
        image: 'nginx:latest'
        ports:
            - '${HTTP_PORT:-8000}:80'
            - '${SSL_PORT:-443}:443'
        environment:
            - SSL_PORT=${SSL_PORT:-443}
            - APP_SERVICE=${APP_SERVICE:-laravel.test}
            - SERVER_NAME=${SERVER_NAME:-localhost}
        volumes:
            - 'sail-nginx:/etc/nginx/certs'
            - './nginx/templates:/etc/nginx/templates'
            - './vendor/ryoluo/sail-ssl/nginx/generate-ssl-cert.sh:/docker-entrypoint.d/99-generate-ssl-cert.sh'
        depends_on:
            - ${APP_SERVICE:-laravel.test}
        networks:
            - sail

that file vendor/ryoluo/sail-ssl/nginx/generate-ssl-cert.sh is present and in container logs present msg 99-generate-ssl-cert.sh: Server certificate has been generated.

Maybe ned to use some specific version for nginx or ryoluo/sail-ssl ?

Are there any ways to press the Enter keyboard key?

I’m working with chrome-php/chrome right now. I have problems when to execute keyboard key press for Enter. Are there any ways to do that ?

I have already trying to execute the code but there are no options. Maybe there are alternatives how to do that ?

below is the code I use to test.

$browserFactory = new BrowserFactory();

// starts headless Chrome
$browser = $browserFactory->createBrowser([
    'windowSize'   => [1920, 1000],
]);

try {
    $page = $browser->createPage();
    $page->setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36');
    $page->navigate('https://www.google.com/')->waitForNavigation();

    try {
        $page->mouse()->find('textarea')->click(); 
        $page->keyboard()
                ->typeText('travel the world'); 
        $page->keyboard()
                 ->typeRawKey('Enter');
               
    } catch (ElementNotFoundException $exception) {
        // element not found
    }

    $pageTitle = $page->evaluate('document.title')->getReturnValue();

    $page->screenshot()->saveToFile('bar.png');

} finally {
    $browser->close();
}

No database selected error – symfony pimcore 11

I am upgraded my pimcore 10 to pimcore 11 then using symfony 5.

My problem is when I am running this command

php ./bin/console pimcore:bundle:install PimcoreAdminBundle

I am experiencing this error

ERROR] An exception occurred while executing a query: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

My database.yaml

doctrine:
  dbal:
    connections:
      default:
        host: localhost
        port: 3306
        user: pmdr_user
        password: password123
        dbname: pomodoro
        mapping_types:
          enum: string
          bit: boolean
        server_version: 10.5.27-MariaDB

Unable to decode input | Laravel | Image Intervention

in following code i am when passing image from my public_path its working but when i am padding another image as URL i am getting error like “Unable to decode input”. i am using Laravel 11, Intervention package version 3 i.e latest & PHP version 8.2

// create an test image from a file
$manager = ImageManager::gd();
$image = $manager->read(public_path('images/templates/id-card.png'));

$anotherimage = $manager->read('https://static-00.iconduck.com/assets.00/user-icon-1024x1024-dtzturco.png');
// resize to 300 x 200 pixel
$anotherimage->resize(300, 200);

// resize only image height to 200 pixel
$anotherimage->resize(height: 200);


// paste another image
$image = $image->place(
    $anotherimage,
    10, 
    10,
    25
);

// Encode the image to JPG format (using encode method properly)
$encodedImage = $image->encode();  // This should work if 'jpg' is passed as a string

// Check if encoding works properly
if (!$encodedImage) {
    return response('Error encoding image', 500);
}

// Stream the image response with correct headers
return Response::make($encodedImage, 200, [
    'Content-Type' => 'image/jpeg',
]);

How to change the placement of categories filter in Magento 2.4.7 from sidebar to top of catalogue page

i’m working with Magento 2.4.7 and using the Minimog theme from Bluesky. Currently, the categories filter is part of the layered navigation on the left side of the catalog pages. I want to move this filter to the top of the main catalog page to make it more accessible and visible.

[the current placment of the categories filter][1]
[where i wanna put them][2]

this is the xml file that collect the filters and place them at the sidebar
app/code/Blueskytechco/LayeredAjax/view/frontend/layout/catalog_category_view_type_layered.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="catalog.leftnav">
            <action method="setTemplate" ifconfig="layered_ajax/general/enable">
                <argument name="template" xsi:type="string">Blueskytechco_LayeredAjax::layer/view.phtml</argument>
            </action>
            <arguments>
                <argument name="view_model" xsi:type="object">BlueskytechcoLayeredAjaxViewModelLayered</argument>
            </arguments>
        </referenceBlock>
        <referenceBlock name="catalog.navigation.renderer">
            <action method="setTemplate" ifconfig="layered_ajax/general/enable">
                <argument name="template" xsi:type="string">Blueskytechco_LayeredAjax::layer/filter.phtml</argument>
            </action>
            <arguments>
                <argument name="view_model" xsi:type="object">BlueskytechcoLayeredAjaxViewModelLayered</argument>
            </arguments>
        </referenceBlock>
        <referenceBlock name="catalog.navigation.state">
            <action method="setTemplate" ifconfig="layered_ajax/general/enable">
                <argument name="template" xsi:type="string">Blueskytechco_LayeredAjax::layer/state.phtml</argument>
            </action>
        </referenceBlock>
        <referenceBlock name="category.products">
            <action method="setTemplate" ifconfig="layered_ajax/general/enable">
                <argument name="template" xsi:type="string">Blueskytechco_LayeredAjax::category/products.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

i need some help so i can make the categories filter render alone and place them at the top of the catalogue page. or maybe there is another way that i didn’t notice if please someone can help me with this.
[1]: https://i.sstatic.net/HdNrltOy.png
[2]: https://i.sstatic.net/F00uWD9V.png

i have tried to Create a New Template File named it category_filter.phtml in app/design/frontend/Bluesky/bluesky_default/Magento_LayeredNavigation/templates/category_filter.phtml

<?php
// Ensure the filter block is loaded
$filterBlock = $block->getLayout()->getBlock('layered-navigation-filter-block');
if ($filterBlock) {
    $filters = $filterBlock->getFilters();
    foreach ($filters as $filter) {
        if ($filter->getRequestVar() == 'cat') {
            echo $filterBlock->getChildBlock('renderer')->render($filter);
        }
    }
}
?>

after that i have updated the catalog_category_view.xml

<referenceContainer name="content">
    <block class="MagentoFrameworkViewElementTemplate" name="category.filter.top" template="Magento_LayeredNavigation::category_filter.phtml" before="-"/>
</referenceContainer>

WooCommerce: conditional message if first order

I’ve got some code working which shows a message at the top of the packing slips if we have a new customer.

However, it’s showing the message for all orders, so I’ve figured my code isn’t getting the right info from WooCommerce to confirm if the customer has previously placed an order.

We’re using HPOS too.

function action_wpo_wcpdf_after_document_label( $wpo_wcpdf_export_template_type, $order ) { 

  if ('packing-slip' != $wpo_wcpdf_export_template_type) { return; }

  $billing_email = $order->get_billing_email();

  if (!$billing_email) {

    return;
  }

  $customer_orders = get_posts( array(
    'numberposts' => -1,
    'exclude'     => array($order->get_id()),
    'meta_key'    => '_billing_email',
    'meta_value'  => $billing_email,
    'post_type'   => wc_get_order_types(),
    'post_status' => array_keys( wc_get_order_statuses() ),
  ) );
      
  if (empty($customer_orders)) { print "n" . '<p class="form-field form-field-wide" style="font-weight: bold;margin-top: -60px;border: 1px solid;width: 90px;padding: 3px 10px 5px 10px;line-height: 1;text-align: center;">New Customer</p>' . "n"; return; }

  else { print "n" . '<p class="form-field form-field-wide" style="font-weight: bold;margin-top: -60px;border: 1px solid;width: 90px;padding: 3px 10px 5px 10px;line-height: 1;text-align: center;">Existing Customer</p>' . "n"; return; }

  return;
} 
         
add_action( 'wpo_wcpdf_after_document_label', 'action_wpo_wcpdf_after_document_label', 10, 2 ); 

How to display each Row of Data from MYSQL to html page each in their own separate div element

This code displays all of them all at once but I want to display them side by side

<div class="main">

<div id="display">  
<?php
if ($result->num_rows > 0) {
        // Loop through each row and display the data
        $divcount = 1;
        while ($row = $result->fetch_assoc()) {
            
            echo '<div id="display' . $divcount++ .'" >';
            echo '<img src="' . $row["photo"] . '" alt="Car Image" style="width:190px;height:180px; max-width:250px;"><br>';
            echo "Name: " . $row["car_brand"] . " " . $row["car_type"] . "<br>";
            echo "Manufactured Date: " . $row["manufactured_date"] . "<br>";
            echo "Price: " . $row["price"] . "<br>";
            echo "Fuel Type: " . $row["fuel_type"] . "<br>";
            echo "Condition: " . $row["condition"] . "<br>";
            echo "Phone No: " . $row["phone_number"] . "<br>";
            echo '</div>';
            
        }
    } else {
        echo "No records found in the database.";
    }
    ?>
    
</div>

Looking for a code that works and a good explanation and point to me for a good resource that can solve other problems like this

Woocommerce plugin not setting taxonomy attribute value on product

I’ve been trying to implement a solution for setting taxonomy attributes on WooCommerce products. This is a the code I wrote:

$product = wc_get_product($product_id);

$taxonomy = 'pa_out-of-stock';
$false_term_name = 'false';
$true_term_name = 'true';

$false_term_id = get_term_by('name', $false_term_name, $taxonomy)->slug;
$true_term_id = get_term_by('name', $true_term_name, $taxonomy)->slug;

$attributes = (array) $product->get_attributes();

if (array_key_exists($taxonomy, $attributes)) {
    foreach (
        $attributes as $key => $attribute
    ) {
        if ($key == $taxonomy) {
            $options = $attribute->get_options();
            $options = array($true_term_id);
            $attribute->set_options($options);
            $attributes[$key] = $attribute;
            break;
        }
    }
    $product->set_attributes($attributes);
}
else {
    $attribute = new WC_Product_Attribute();

    $attribute->set_id(sizeof($attributes) + 1);
    $attribute->set_name($taxonomy);
    $attribute->set_options(array($false_term_id));
    $attribute->set_position(sizeof($attributes) + 1);
    $attribute->set_visible(true);
    $attribute->set_variation(false);
    $attributes[] = $attribute;

    $product->set_attributes($attributes);
}

$product->save();

I printed out the $product object and the set_options() function seems to be changing the value. But after the $product->save() function is called there seems to be no changes, the attribute term doesn’t seem to change on the product. I checked the term ID’s, they are correct. I checked the taxonomy slug, it also correct. The just seems that the saving is not working. Any ideas why this could be happening?

How to describe anonymous classes and methods?

I need to run tests on a certain class, but adding a method that was not originally present.

Previously this need could be satisfied using MockBuilder::addMethods(), but this method has been deprecated.

So, currently, the simplest alternatives are to define (somewhere) a new class or to use an anonymous class, which extends the class affected by the test and implements the new method.

In my case, I extend the DropdownHelper class by adding the (non-existent in the original) getLastLink() method:

$Dropdown = new class (new View()) extends DropdownHelper {
   public function getLastLink(): string
   {
      return $this->_links ? end($this->_links) : '';
   }
};

Now the problem is calling

$Dropdown->getLastLink()

phpstan gives me this error:

Call to an undefined method ClimatCoreViewHelperDropdownHelper::getLastLink().

How can I properly document this? I would like to avoid defining another class elsewhere and using the anonymous one (and I would like to avoid suppressing the error, but rather document the anonymous class correctly).

Thanks.

In PHP I don’t get the result I have in PHPmyAdmin [duplicate]

I am trying to use MySQL CONCAT_WS in a PDO Prepared Statement. I tested the query inside of phpMyAdmin and it works perfectly but not in a PDO Prepared Statement.

Here is the phpMyAdmin query which gives me the result i am looking for.

SELECT CONCAT_WS(',', `forum_tags`) AS ftags FROM `forum_topics` WHERE `forum_id` > 0

And the result i am looking for

phpMyAdmin result

I am having difficulty replacating that in my PDO Prepared Statement. Here is my current PDO code

  $zero = 0;
    
  $sql = "SELECT CONCAT_WS(',', `forum_tags`) AS ftags FROM `forum_topics` WHERE `forum_id` > :z;";
  
  $stmt = $this->pdo->prepare($sql);
   
  $stmt->execute([
                  ':z' => $zero
                 ]);  
       
  $results = $stmt->fetch(); //also tried fetchAll() as a test
  
  if(is_array($results))
  {
      
    return $results;  
      
  }//close if is array
      
    
  return false; 

What is the proper to way perform this with PDO Prepared Statement?

Thank you.

Quantity updating issue in PHP

I’m developing an e commerce website Laravel PHP. In my cart page when I click update quantity its suddenly coming again into previous quantity value. But this happen only in first product in cart products list. Second, third and for other all products this update quantity working properly. Whatever comes to first in cart products list, quantity value comes to previous value when click update button.
cart blade
[

@extends('layout')

@section('content')
<section class="container mx-auto py-16 px-4 lg:px-8">
    <h1 class="text-3xl font-semibold mb-6">Shopping Cart</h1>

    @if(empty($cart))
        <p class="text-gray-500">Your cart is empty.</p>
        <a href="/shop" class="text-blue-500">Continue Shopping</a>

        <!-- Show total price (as zero) and proceed to checkout button even when the cart is empty -->
        <div class="mt-6">
            <p class="text-xl font-semibold">Total Price: <span class="text-green-500">LKR0.00</span></p>
        </div>

        <button 
            class="bg-yellow-500 text-white px-6 py-3 rounded-lg mt-6 block text-center opacity-50 cursor-not-allowed" 
            disabled>
            Proceed to Checkout
        </button>

    @else
    <!-- Form to handle selected products -->
    <form action="{{ route('checkout.show') }}" method="GET" id="checkout-form">
        <table class="w-full text-left border-collapse">
            <thead>
                <tr>
                    <th class="border-b py-4">Select</th>
                    <th class="border-b py-4">Image</th>
                    <th class="border-b py-4">Name</th>
                    <th class="border-b py-4">Price</th>
                    <th class="border-b py-4">Quantity</th>
                    <th class="border-b py-4"></th>
                </tr>
            </thead>
            <tbody id="cart-items">
                @foreach($cart as $productId => $item)
                <tr>
                    <td class="py-4">
                        <input type="checkbox" name="selected[]" class="product-checkbox" value="{{ $productId }}" data-price="{{ $item['price'] * $item['quantity'] }}" onchange="updateTotalPrice()">
                    </td>
                    <td class="py-4">
                        <img src="{{ asset('storage/' . $item['image']) }}" alt="{{ $item['name'] }}" class="w-20">
                    </td>
                    <td class="py-4">{{ $item['name'] }}</td>
                    <td class="py-4">LKR{{ number_format($item['price'], 2) }}</td>
                    <td class="py-4">
                        <form action="{{ route('cart.update', $productId) }}" method="POST">
                            @csrf
                            @method('PUT')
                            <input type="number" name="quantity" value="{{ $item['quantity'] }}" min="1" class="border border-gray-300 rounded px-4 py-2 w-20">
                            <button type="submit" class="text-blue-500 hover:text-blue-700 ml-2">Update</button>
                        </form>
                    </td>

                    <td class="py-4">
                        <form action="{{ route('cart.remove', $productId) }}" method="POST">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="text-red-500 hover:text-red-700">Remove</button>
                        </form>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>

        <div class="mt-6">
            <p class="text-xl font-semibold">
                Selected Total Price: <span class="text-green-500" id="selected-total">LKR0.00</span>
            </p>
        </div>

        <form action="{{ route('cart.clear') }}" method="POST" class="mt-4">
            @csrf
            <button type="submit" class="text-red-500 hover:text-red-700">Clear Cart</button>
        </form>

        <!-- Submit button to proceed to checkout -->
        <button type="submit" 
            class="bg-yellow-500 text-white px-6 py-3 rounded-lg mt-6 block text-center opacity-50 cursor-not-allowed" 
            id="checkout-button" 
            disabled>
            Proceed to Checkout
        </button>
    </form>
    @endif
</section>

<script>
    function updateTotalPrice() {
        let totalPrice = 0;
        let isSelected = false;  // Flag to check if at least one checkbox is selected
        document.querySelectorAll('.product-checkbox').forEach(checkbox => {
            if (checkbox.checked) {
                totalPrice += parseFloat(checkbox.dataset.price);
                isSelected = true;  // Set flag to true if any checkbox is selected
            }
        });

        // Update total price
        document.getElementById('selected-total').innerText = 'LKR' + totalPrice.toFixed(2);

        // Enable or disable the Proceed to Checkout button based on selection
        const checkoutButton = document.getElementById('checkout-button');
        if (isSelected) {
            checkoutButton.classList.remove('opacity-50', 'cursor-not-allowed');
            checkoutButton.classList.add('opacity-100', 'cursor-pointer');
            checkoutButton.removeAttribute('disabled');
        } else {
            checkoutButton.classList.add('opacity-50', 'cursor-not-allowed');
            checkoutButton.classList.remove('opacity-100', 'cursor-pointer');
            checkoutButton.setAttribute('disabled', true);
        }
    }
    document.querySelectorAll('.update-button').forEach(button => {
    button.addEventListener('click', function () {
        const productId = this.getAttribute('data-product-id');
        const quantityInput = document.querySelector(`.quantity-input[data-product-id="${productId}"]`);
        const quantity = quantityInput.value;

        fetch(`/cart/update/${productId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify({ quantity: quantity })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update the total price in the checkbox's data attribute
                const productCheckbox = document.querySelector(`.product-checkbox[value="${productId}"]`);
                productCheckbox.dataset.price = data.updatedPrice;

                // Recalculate the total price
                updateTotalPrice();

                alert(data.message);
            } else {
                alert('Failed to update the cart.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
});

</script>

@endsection

]

controller
[

<?php

namespace AppHttpControllers;

use AppModelsProduct;
use IlluminateHttpRequest;
use IlluminateSupportFacadesSession;

class CartController extends Controller
{
    /**
     * Add product to the cart.
     */
    public function addToCart(Request $request)
    {
        // Get the cart from the session, or initialize an empty array if not set
        $cart = Session::get('cart', []);

        // Retrieve the product data from the request
        $productId = $request->input('product_id');
        $productName = $request->input('name');
        $productPrice = $request->input('price');
        $productImage = $request->input('image');
        $quantity = (int) $request->input('quantity', 1);

        // Validate the product data
        if (!$productId || !$productName || !$productPrice || !$productImage || $quantity < 1) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid product information.',
            ]);
        }

        // If the product is already in the cart, update the quantity
        if (isset($cart[$productId])) {
            $cart[$productId]['quantity'] += $quantity; // Increment quantity
        } else {
            // Otherwise, add the product to the cart
            $cart[$productId] = [
                'name' => $productName,
                'price' => $productPrice,
                'image' => $productImage,
                'quantity' => $quantity,
            ];
        }

        // Save the updated cart back to the session
        Session::put('cart', $cart);

        // Get updated cart count
        $cartCount = array_sum(array_column($cart, 'quantity'));

        return response()->json([
            'success' => true,
            'message' => 'Product added to cart!',
            'cartCount' => $cartCount, // Return the updated cart count
        ]);
    }

    /**
     * Show the cart page.
     */
    public function showCart()
    {
        $cart = Session::get('cart', []);
        $totalPrice = 0;

        foreach ($cart as $item) {
            $totalPrice += $item['price'] * $item['quantity'];
        }

        return view('cart', ['cart' => $cart, 'totalPrice' => $totalPrice]);
    }

    /**
     * Remove a product from the cart.
     */
    public function removeFromCart($productId)
    {
        $cart = Session::get('cart', []);

        // Check if the product exists in the cart
        if (isset($cart[$productId])) {
            // Remove the product from the cart
            unset($cart[$productId]);

            // Save the updated cart to the session
            Session::put('cart', $cart);
        }

        // Redirect back to the cart page
        return redirect()->route('cart.show');
    }

    /**
     * Clear the entire cart.
     */
    public function clearCart()
    {
        // Clear the cart from the session
        Session::forget('cart');

        // Redirect back to the cart page with a success message
        return redirect()->route('cart.show')->with('success', 'Cart has been cleared!');
    }

    /**
 * Update the quantity of a product in the cart.
 */
public function updateCart(Request $request, $productId)
{
    $cart = Session::get('cart', []);

    // Validate product ID and quantity
    $quantity = (int) $request->input('quantity');
    if (!isset($cart[$productId]) || $quantity < 1) {
        return redirect()->route('cart.show')->with('error', 'Invalid product or quantity.');
    }

    // Update the quantity in the cart
    $cart[$productId]['quantity'] = $quantity;

    // Save updated cart to session
    Session::put('cart', $cart);

    return redirect()->route('cart.show')->with('success', 'Cart updated successfully!');
}



    /**
     * Get the total count of products in the cart.
     */
    public function getCartCount()
    {
        $cart = session()->get('cart', []);
        $count = array_sum(array_column($cart, 'quantity'));
        return response()->json(['count' => $count]);
    }
}

]

I tried change update method in controller, but didnt work.

High CPU Usage by kdevtmpfsi Process in Docker Setup (PHP Container)

I am encountering an issue with my Docker setup where the kdevtmpfsi process is consuming 100% CPU. Here’s my setup:

I am using a multi-container setup defined in Docker Compose with services for PHP (using PHP 8.2), Nginx, MySQL, and RabbitMQ.
The api_php container is built from the php:8.2-fpm base image and configured with various extensions and Composer.
Other containers like api_mysql, api_nginx, and api_rabbitmq are running fine.
Here’s the problem:

When the api_php container is enabled and running, the kdevtmpfsi process consumes 100% of the CPU.
If I stop or disable the api_php container, the CPU usage immediately drops to normal.
Here’s a snippet of my api_php Dockerfile and Docker Compose configuration:

Dockerfile (PHP)

# Use the official PHP image with PHP 8.2 as the base image
FROM php:8.2-fpm

# Install PHP extensions and dependencies
RUN apt-get update && 
    apt-get install -y 
        libicu-dev 
        cron 
        vim 
        supervisor 
        git 
        zip 
        unzip 
        imagemagick 
        libmagickwand-dev 
        zlib1g-dev 
        libpng-dev && 
    pecl install imagick && 
    docker-php-ext-enable imagick && 
    docker-php-ext-install pdo_mysql sockets intl gd

# Install Composer
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && 
    php composer-setup.php --install-dir=/usr/local/bin --filename=composer && 
    php -r "unlink('composer-setup.php');"

# Set the environment variables for libsodium
ENV LIBSODIUM_CFLAGS="-I/usr/include/libsodium"
ENV LIBSODIUM_LIBS="-lsodium"
ENV ZLIB_CFLAGS="-I/usr/local/include"
ENV ZLIB_LIBS="-L/usr/local/lib -lz"
ENV PNG_CFLAGS="-I/usr/local/include"
ENV PNG_LIBS="-L/usr/local/lib -lpng"
ENV MAGICKWAND_CONFIG_PATH /usr/bin/MagickWand-config

# Set the working directory in the container
WORKDIR /var/www/html

# Copy the remaining application files to the container
COPY . .

# Expose port 9000 for PHP-FPM
EXPOSE 9000

# Start PHP-FPM
CMD ["php-fpm"]

Docker Compose (relevant portion)

version: '3'
services:
  api_nginx:
    container_name: "api_nginx"
    restart: unless-stopped
    image: api_nginx
    build:
      context: ./docker/nginx
      dockerfile: Dockerfile
    ports:
      - 8081:80
    volumes:
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
      - ./public:/var/www/html/public
    depends_on:
      - api_php
    networks:
      - api_network
  api_php:
    container_name: "api_php"
    restart: unless-stopped
    image: "api_php"
    build:
      context: ./docker/php
      dockerfile: Dockerfile
    ports:
      - "9001:9000"
    volumes:
      - ./docker/supervisord:/etc/supervisor/conf.d
      - .:/var/www/html
    command: sh -c "composer install --no-dev --optimize-autoloader && /usr/bin/supervisord"
    networks:
      - api_network
  api_mysql:
    container_name: "api_mysql"
    restart: unless-stopped
    image: api_mysql
    build:
      context: ./docker/mysql
      dockerfile: Dockerfile
    command: --default-authentication-plugin=mysql_native_password
    env_file:
      - docker/mysql/.env
    volumes:
      - ./docker/mysql/data:/var/lib/mysql
    ports:
      - 33061:3306
    environment:
      MYSQL_LOG_BIN_TRUST_FUNCTION_CREATORS: "1"
    networks:
      - api_network
  api_rabbitmq:
    container_name: "api_rabbitmq"
    restart: unless-stopped
    image: "api_rabbitmq"
    build:
      context: ./docker/rabbitmq
      dockerfile: Dockerfile
    environment:
      RABBITMQ_DEFAULT_USER: *****
      RABBITMQ_DEFAULT_PASS: ****
    volumes:
      - ./docker/rabbitmq/data:/var/lib/rabbitmq/
    ports:
      - 15001:15672
    networks:
      - api_network
networks:
  api_network:
    external: true

I suspect the issue might be due to:

  • Malware or a cryptominer (kdevtmpfsi seems suspicious).
  • Some misconfiguration in the api_php container leading to abnormal resource usage.
  • Here are the steps I’ve taken so far:

Stopped the container to confirm it’s the source of the issue.
Checked system logs for clues but found nothing definitive.
Scanned for any malicious files or processes in the host system and containers.

Questions:

  • What could be causing the kdevtmpfsi process to consume so much CPU – when the api_php container is running?
  • How can I identify if this is related to malware or a misconfiguration?
  • What steps can I take to resolve this issue while ensuring my system and containers remain secure?

Any insights or advice would be greatly appreciated!

CPU usage

I tried the following steps to resolve the issue:

  • Rebuild the container: I removed the existing api_php container, rebuilt it, and restarted the setup, hoping it would resolve the high CPU usage caused by the kdevtmpfsi process.
  • Scan for malware: I attempted to scan the containers and the host system for any potential malware, particularly targeting the kdevtmpfsi process. I suspected the process could be related to a cryptominer or malicious activity.
  • Remove malware: After scanning, I removed any identified malicious files or processes, but the issue keeps coming back, with kdevtmpfsi returning to 100% CPU usage.

$_SESSION[‘username’] is NULL [duplicate]

I am trying to learn PHP and I am steadely on my way by following a course about PHP.
For exercise I have to build an app that requires login and sessions.

In my UserController I use the code below to login:

<?php

class UserController extends Controller {

public function login() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $username = $_POST['username'];
        $password = $_POST['password'];

        $userModel = $this->model('User');
        $user = $userModel->authenticate($username, $password);
        
        if ($user) {
            $_SESSION['user'] = $user;
            //Redirect.
            header('Location: /home/index');
            exit();
        } else {
            $error = "Invalid username or password";
            $this->view('users/login',['heading' => 'User Login']);
           
        }
    } else {
        $this->view('users/login',['heading' => 'User Login']);
    }
}

?>

My User Model looks like this:

<?php
class User extends Database {
    //Check authentication of the user.
    public function authenticate($username, $password) {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE username = :username");
        //// Retrieve all results from the query as an associative array (PDO::FETCH_ASSOC). Each record is returned as an array with column names as keys.
        $stmt->bindParam(':username', $username);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            return $user;
        }
        return false;
    }
    ?>

The problem is that the $_SESSION[‘user’][‘username’] gets the value NULL.

I hop you can help me resolve this issue.

How to Implement Card-Based Transactions with PayPal Payouts?

I’m working on a Laravel project where I need to implement the following functionality:

  1. The acceptor (user receiving payments) provides their card details
    (card number, expiry date, CVV) in the application.
  2. These card details are sent to PayPal, and I store the returned
    token securely for future use. The sender (user making the payment)
    also provides their card details, and payments are processed as
    follows: 90% of the payment goes to the acceptor. 10% of the payment
    goes to the admin as a fee.

Initially, I considered using PayPal Payouts, as it supports splitting payments and managing multiple recipients. However, the recipient_type in PayPal Payouts only allows EMAIL, PHONE, or PAYPAL_ID. When I send the acceptor’s card details to PayPal to generate a token, PayPal doesn’t return any of these recipient types (EMAIL, PHONE, or PAYPAL_ID) that I could use to send payouts.

Is there a way to use PayPal Payouts or any other PayPal API for this functionality? If not, what would be the best approach to handle this type of payment flow where both parties provide card details, and the payment is split between the acceptor and the admin?

Any guidance or recommendations would be highly appreciated!