PHP/Laravel groupBy is extremely slow

Our customers pay for licenses that run for some time, e.g. 6 months.
Example:

Product: product1
Payment date: 2024-01-01
Start date: 2024-01-01
End date: 2024-03-31
Total excluding tax: $29.99

We want to know how much of this amount goes towards which month.
So we calculate the number of days (in this case: 31 + 29 + 31 = 91) and divide the amount by this number to get the amount per day ($29.99 / 91 days = $0.32956 / day), and then we get:

January 2024: 31 * $0.32956 = $10.216
February 2024: 29 * $0.32956 = $9.557
March 2024: 31 * $0.32956 = $10.216

Here, the numbers are very similar for the sake of the example, but usually, we’d of course have licenses that start in the middle of the month, so the numbers can be very different.

We have thousands of such licenses for different products, so it’s a grouping both by product and by month, which would be very slow to do in the database (MariaDB).
For this reason, we want to do a single, simple SQL SELECT that fetches all licenses, and then do the grouping in PHP/Laravel code.
Yet for some reason, this is excruciatingly slow.
The code looks like this:


    public function revenueWaterfall(Request $request)
    {
        $products = $request->get('product_id') == 'all' ? Products::all() : Product::whereId($request->get('product_id'))->get();

        $bookedPeriodTo = $request->get('bookedPeriodTo');
        $bookedPeriodFrom = $request->get('bookedPeriodFrom');

        $productId = $products->count() == 1 ? $products->first()->id : null;

        $allData = Invoice::getAllForPeriod(Carbon::parse($bookedPeriodFrom), Carbon::parse($bookedPeriodTo), $productId)->groupBy('product_id')->sort();

        $splitValues = $allData->map(function ($productPayments) {
                    $total = $productPayments->sum('total_excluding_tax');
                    $months = $this->splitRevenueByMonth($productPayments);
                    return array_merge($months, ['total' => $total]);
                });
        return response()->json($splitValues);
    }

    function splitRevenueByMonth($payments)
    {
        $byMonth = [];

        foreach ($payments as $payment) {
            $startDay = Carbon::parse($payment->period_start)->startOfDay();
            $endDay = Carbon::parse($payment->period_end)->startOfDay();
            $daysInPeriod = $endDay->diffInDays($startDay);

            if ($daysInPeriod < 1) {
                // Handle invalid period
                throw new Exception("Invalid period detected");
            }

            $amountPerDay = $payment->total_excluding_tax / $daysInPeriod;

            for ($i = clone $startDay; $i->lessThan($endDay); $i->addDay()) {
                $month = $i->format('M Y');
                $byMonth[$month] = ($byMonth[$month] ?? 0) + $amountPerDay;
            }
        }

        return $byMonth;
    }

Actually, when I look at the code now (I slightly simplified it for the sake of this question), it seems like the grouping by product is missing.
What we would like to have is an output like this:

{
"product1":
    {
        "January 2024": 2255209.2525,
        "February 2024: 5252525.5336,
        "March 2024": 35363.3636
    },
"product2":
    {
        "December 2023": 309906.3532,
        "January 2024": 3059035.9092
    }
}

etc.

How to run a Php web file in kali linux

I am trying to open up my php web files for my project in kali (o.s). I was previously using Xampp in Windows which run well however when i try to install Xampp in kali it gives me a warning not a secure program. Is there any other method or is it possible to use the apache2 service.Any advice on how to solve this problem will be much appreciated.

Installing Xampp became an issue and i could not run my php web files.I have tried using the apache2 service however with no luck

Why Opentelemetry spans with same trace ids could have different transaction ids in the Elastic APM?

I see a strange behavior for Opentelemetry integration. We have applications in PHP and Go which are linked with GRPC. I’ve made a manual Opentelemetry integration for PHP (with GRPC transport). However there is a strange situation when some of spans are not linked (but I’m absolutely sure that they should) despite the same trace id. Metadata tab for them shows different transaction ids but the same trace id. What could be a reason for such a behavior? I am able to find all of them by trace id on APM’s Traces tab. Also, in some endpoints (also PHP http -> PHP GRPC Client -> Go) everything is correct: I see the same transaction id, same trace id and all the spans for the operation on one screen.

enter image description here

Accessing Google Cloud SQL instance from remote server using php

I’m using msqli_connect (…) to connect from my server (IP-a) to a Google Cloud SQL instance with Public IP (IP-g). All the GS firewall rules are in place to allow this, SSL is not used currently. However, I consistently get “Connection refused”. I cannot seem to find any further detail on this: I can’t see any relevant GC error/warning logging, and there appears to be no further client-side detail available.

Looking though the web and ChatGPT, I can see this a common problem (exacerbated but the lack of debug detail I think). However, I’ve not found any new insights into how to address this problem.

From my office PC (Unbuntu) I can run mysql with the relevant parameters and get a successful connection, where I can see and interrogate the target database. But I cannot seem to do this from a SSH on my server (IP-a).

Essential code:

<?php
....

$dbhost = [IP-g]
$dbport = 3306;
$dbname = [DB-name]
$dbuser = [DB-user]
$dbpass = [DB-pass]
//
echo "<p>About to get DB... host='$dbhost'</p>n";
//
mysqli_report (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//
$myaddr = $_SERVER['SERVER_ADDR'];
echo "<p>+++(ip=$myaddr): Got here: host = '$dbhost', user='$dbuser', pass='$dbpass', name='$dbase',  port='$dbport'.</p>n";
//
try {
     $dbid = mysqli_connect ($dbhost, $dbuser, $dbpass, $dbname, $dbport);          
     echo "<p>1:dbid = '<pre>" . print_r ($dbid, true) . "</pre>'</p>n";
    }    
catch (Exception $e) {
    echo 'Message: ' . $e->getMessage();
    echo "<p>Get db failed.. mce = '" . mysqli_connect_error() . ".</p>n";
    die ('bye');
   }
// Success!
echo "<p>OK:dbid = '<pre>" . print_r ($this->dbid, true) . "</pre>'</p>n";
//
...
?>

OUTPUT:

About to get DB... host=[IP-g]

DB::Got here: host = '[IP-g]', name=[DB-name], user=[DB-user], pass=[DB-pass], port=]DB-port].

+++(ip=[IP-a]: Got here: host = [IP-g], user=[DB-user], pass=[DB-pass], name=[DB-name], port='3306'.
Message: Connection refused

Get db failed.. mce = 'Connection refused'.
bye

Stripe – Immediately charging

I want create a charge without a confirmation on the front end. That means that a customer fills out the card details via React’s CardElement and then should click on a booking button. Is this possible without a confirm page to confirm the payment intend? The confirmation should work automatically?

I have implemented $stripe->charges->create(...) in PHP, but this did not work.

I’m using React & PHP on server side.

Ajax call showing data in console.log but not returning data

I’m trying to work on a simple Ajax call and I’m unable to figure out what’s gone wrong. The ajax call is successful but nothing is returning. When I console.log(response), it displays the JSON in my console though. I’m using fullcalendar library and Ajax call not returning a response to the events object

Following is my action function written in functions.php file

function get_order_events() { 
$args = array( 
        'status' => array('processing', 'completed', 'on-hold'), 
        'orderby' => 'date',
        'limit' => -1, 
        'type' => 'shop_order', );
 $customer_orders = wc_get_orders($args); $events = array(); foreach ($customer_orders as $order) 
{ 
   foreach ($order->get_items() as $item_id => $item_values) { 
        $product_id =$item_values['product_id'];        
        // Get start and end dates from post meta
        $start_date = wc_get_order_item_meta($item_id, 'Check-in', true);
        $end_date = wc_get_order_item_meta($item_id, 'Checkout', true);

        // Add event to the array
        $events[] = array(
            'title' => get_the_title($product_id).' : Booked',
            'start' => $start_date,
            'end' => $end_date,
        );
    } 
}
// echo json_encode($events);
wp_send_json_success($events);
wp_die();
// return json_encode($events);
}

add_action('wp_ajax_get_order_events', 'get_order_events'); add_action('wp_ajax_nopriv_get_order_events', 'get_order_events');

Following is my js code

    var link = admin_object.ajax_url;    
    $("#calendar").fullCalendar({
        initialView: 'dayGridMonth',
        height: 650,
        events: function (_info, successCallback, failureCallback) {
            jQuery.ajax({
                url: link,
                type: 'POST', // Use POST method

                dataType: 'json',
                data: {
                    action: 'get_order_events'
                },
                success: function (response) {
                    console.log(response.data);
                    successCallback(response.data);
                    // $('#output').html(response.data);
                },
                error: function (error) {
                    console.log("Error");
                    failureCallback(error);
                }
            });
        }
    });

Problem with paypal gateway moodle plugin

I’m new to moodle and I want to use paypal, mtn and airtel for course payments. I’m able to see the other two; i.e, Mtn and Airtel, under “select payment type”, but I can’t see paypal.Select payment type

I tried disabling the other two and it showed, I enabled them again and it stopped showing again. I disabled them again to see if it will show but this time it didn’t show. check these screen shorts.After disabling Mtn and Airtel,Paypal is enabled,This the payment account.

I know I was suppose to post on the moodle forum but I just created my moodle account and still waiting for the confirmation email which may never come and I’m running out of time. can anyone point me in the right direction coz I’ve tried searching on the internet and can’t find anything related to what I’m facing. Thanks in advance.

Sticky Product Options(Variation Attributes) on the woocommerce product page

I want to show the product variation options at the bottom of the screen on the product page in a woocoommerce store. It’ll be a sticky section which will show product options and the add to cart button.

Here is the screenshot of the section I want :

enter image description here

Here is the reference website link.

Here is the code I tried, it added the price and the add to cart button. But Instead of price I want to show the product options and add to cart button.

The Code I have tried:

add_action( 'wp_footer', 'sticky_add_to_cart_button' );
    
function sticky_add_to_cart_button() {
    if ( ! is_product() ) {
        return;
    }
    global $product;
    
    if ( $product->is_type( 'variable' ) ) {
        $variation_attributes = $product->get_variation_attributes();
        $add_to_cart_url = esc_url( $product->add_to_cart_url() );
        $price = $product->get_price_html();
        ?>
        <style>
        .sticky-add-to-cart-section {
            position: fixed;
            bottom: 0;
            right: 0;
            left: 0;
            z-index: 9999;
            display: flex;
            align-items: center;
            padding: 5px 20px;
            background-color: white;
            box-shadow: 0px 2px 10px #27272780;
            -webkit-box-shadow: 0px 2px 10px #27272780;
            transition: 0.6s;
            -moz-box-shadow: 0px 2px 10px #27272780;
        }
        .sticky-add-to-cart-button {
            width: 50%;
            padding: 10px 0px;
        }
        .sticky-add-to-cart-price {
            width: 50%;
            text-align: center;
            font-size: 1em;
            color: #313131;
            padding: 18px 0px;
        }
        .sticky-variation-attributes {
            width: 100%;
            text-align: center;
            padding: 10px 0px;
        }
        </style>
        <script>
        jQuery(document).ready(function($) {
            var addToCartButton = jQuery('button.single_add_to_cart_button, button[name="checkout"]');
            if (!isElementInViewport(addToCartButton)) {
                var stickySection = jQuery('<div class="sticky-add-to-cart-section">');
                var stickyButton = addToCartButton.clone();
                stickyButton.addClass('sticky-add-to-cart-button');
                var stickyPrice = jQuery('<div class="sticky-add-to-cart-price">').html('<?php echo $price; ?>');
                var variationAttributes = '<div class="sticky-variation-attributes">';
                $.each(<?php echo json_encode($variation_attributes); ?>, function(key, value) {
                    variationAttributes += '<span>' + key + ': ' + value + '</span>';
                });
                variationAttributes += '</div>';
                stickySection.append(variationAttributes);
                stickySection.append(stickyPrice);
                stickySection.append(stickyButton);
                jQuery('body').append(stickySection);
        
                stickyButton.click(function() {
                    addToCartButton.click();
                });
            }
        
            function isElementInViewport(el) {
                var rect = el[0].getBoundingClientRect();
                return (
                    rect.top >= 0 &&
                    rect.left >= 0 &&
                    rect.bottom <= jQuery(window).height() &&
                    rect.right <= jQuery(window).width()
                );
            }
        });
        </script>
        <?php
    }
}

How to answer to ajax request while receiving MQTT messages

I’m fairly new to PHP and MQTT and I’m trying to figure out how to answer to an Ajax request (from the JavaScript front-end) while receiving MQTT messages. The goal is to update the web page with the new data received. I’m aware I can use WebSockets and send the incoming messages directly from the PHP page, but for several reasons I don’t want to use WebSockets here.

So far, here the code I use to answer to Ajax requests:

<?php
$result = [];
$result['success'] = false;
$result['message'] = "unknown";

if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'quit':
            $msg = shell_exec('sudo systemctl stop startup.service');
            $result['success'] = true;
            $result['message'] = $msg;
            break;

        case 'restart':
            $msg = shell_exec('sudo systemctl restart startup.service');
            $result['success'] = true;
            $result['message'] = $msg;
            break;

        case "do-something":
            // do something!
            $result['success'] = "true|false";
            $result['message'] = "blabla";
            break;    
    }

    echo json_encode($result);
}

and here the code I use to receive MQTT messages:

<?php 
require('vendor/autoload.php');
use PhpMqttClientMqttClient;
use PhpMqttClientConnectionSettings;

$server   = '<address>';
$port     = 1883;
$clientId = 'id';
$username = '<user>';
$password = '<password>';

$mqtt = new MqttClient($server, $port, $clientId);

$connectionSettings = (new ConnectionSettings)
  ->setUsername($username)
  ->setPassword($password)
  ->setKeepAliveInterval(60)
  ->setLastWillQualityOfService(1);

$mqtt->connect($connectionSettings, true);
$mqtt->subscribe('wsc/power', function ($topic, $message) {
    printf("Received message on topic [%s]: %sn", $topic, $message);
}, 0);
$mqtt->loop(true);

What I don’t understand is how to join the two snippets.
The MQTT one enables its own loop so any instruction placed after $mqtt->loop(true); is not executed.

How to handle async requests while the loop is active?

PHP Problems, I Cant Solve

First of all, I’m sorry for my bad English.

I prepared a florist script with PHP. I save the images in the images folder in the management panel and fetch the images as follows:

<img src="<?= $admin_url; ?>images/products/image.jpg">

When I did it this way, I kept getting the following error: Cross-Origin Read Blocking.
Ben de şöyle değiştirdim:

<img src="<?php echo $admin_url; ?>images/products/image.jpg">

Actually, I thought the problem was solved because I could see the pictures and the site was working. After a while it started giving the same error again. So this time I changed it like this:

<img src="https://adminpanel.com/images/products/image.jpg">

This time, like the previous one, it got better for a while, then it broke down again and now it’s like this and it’s not working either. As I said, it gives CORB error and I cannot see the images I uploaded to my site.

In short, I couldn’t fix it no matter what I did and this situation was really starting to bother me. Can you help me, please?

The exact code I’m trying to take pictures of is now as follows:

$getProducts = getProductsIndex();
foreach($getProducts as $a) {
   $product_id = $a['id'];
   $getImageQuery = $db -> query("SELECT * FROM product_imgs WHERE product = '$product_id' ORDER BY id DESC LIMIT 1");
   $getImage = $getImageQuery -> fetch();
   echo '<div class="shop-item col-lg-4 col-md-4 col-sm-12">
   <div class="inner-box">
   <div class="image">
   <a href="urun?value=' . encrypt($product_id) . '" style="display: inline-block; width: 305px; height: 285px;"><img src="https://admin.seydisehircicekci.com/images/products/' . $getImage['img'] . '" alt="Ürün Görseli" style="width: 100%; height: 100%;" /></a>
   </div>
   <div class="lower-content">
   <h6><a href="urun?value=' . encrypt($product_id) . '">' . $a['name'] . '</a></h6>
   <div class="d-flex justify-content-between align-items-center">
   <div class="price">₺ ' . $a['price'] . '</div>
   </div>
   </div>
   </div>
   </div>';
}

Thanks in advance to everyone who helps!

I was trying to fetch images from the admin panel to my website but I encountered the CORB error many times and could not fetch in the images.

cannot login authentication laravel middleware

Every time I try to log in I always return to the login page i cant redirect to my dashboard.I have tried dd() and Auth::check and the results are all success

here my AuthController

use AppHttpControllersController;

use AppModelsUser;
use IlluminateHttpRedirectResponse;
use IlluminateHttpRequest;

use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesRedirect;

    public function loginProses(Request $request): RedirectResponse
    {
        $request->validate([
            'email'=>'required',
            'password'=>'required'
        ],[
            'email.required'=>'Email wajib diisi',
            'password.required'=>'Password wajib diisi',
        ]);

        $infologin = [
            'email'=>$request->email,
            'password'=>$request->password,
        ];

        if (Auth::attempt($infologin)) {
            $request->session()->regenerate();
            // if (Auth::check()) {
            //     return "success";
            // } else {
            //     return "not";
            // }
            return redirect()->intended('dashboard');
            // dd($infologin);
        }else{
            return redirect('/laravel')->withErrors('Username atau Password Salah')->withInput();
        }
    }

my DashboardController that I want to go to

use AppModelsUser;
use AppModelsBuku;
use AppModelsKategori;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

    public function index()
    {
        $totalBooks = Buku::count();
        return view('backend.index', ['totalBooks' => $totalBooks]);
    }

my web Route

use IlluminateSupportFacadesRoute;
use AppHttpControllersAuthController;
use AppHttpControllersDashboardController;
use AppHttpControllersBukuController;
use AppHttpControllersKategoriController;
use AppHttpControllersUsersController;

Route::group(['middleware' => 'auth'], function (){
    Route::resource('dashboard', AppHttpControllersDashboardController::class);
    Route::resource('buku', AppHttpControllersBukuController::class);
    Route::resource('kategori', AppHttpControllersKategoriController::class);
    Route::delete('/logout', [AuthController::class, 'logout'])->name('logout');
});

I want to access the dashboard page that I gave the auth middleware

how to get set-cookie from response PHP? [duplicate]

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, '$url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$postfield");
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

$headers = array();
$headers[] = 'Accept: application/json';
some header array 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

how to get set-cookie from this request ?
i want get cookie from this request

Laravel. Disable system migration create_password_reset_tokens_table

I have a Laravel project. I already have a database with system tables: users, migrations, jobs, etc. However, when I try to run the command

php artisan migrate 

I get an error

create_password_reset_tokens_table - FAIL 

I don’t want to do this migration. How can I skip it or turn it off in Laravel configuration files? Is far as I understand, it comes with the Laravel/UI package and therefore it makes no sense to remove it from the vendor because the composer will download it anyway.

error in codeiginiter while running the project [closed]

Fatal error: During inheritance of SessionHandlerInterface: Uncaught ErrorException: Return type of CodeIgniterSessionHandlersFileHandler::gc($maxlifetime): bool should either be compatible with SessionHandlerInterface::gc(int $max_lifetime): int|false, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:xampphtdocsgayatree-admin-panelsystemSessionHandlersFileHandler.php:333 Stack trace: #0 C:xampphtdocsgayatree-admin-panelsystemSessionHandlersFileHandler.php(21): CodeIgniterDebugExceptions->errorHandler(8192, ‘Return type of …’, ‘C:xampphtdocs…’, 333) #1 C:xampphtdocsgayatree-admin-panelsystemAutoloaderAutoloader.php(294): include_once(‘C:xampphtdocs…’) #2 C:xampphtdocsgayatree-admin-panelsystemAutoloaderAutoloader.php(265): CodeIgniterAutoloaderAutoloader->includeFile(‘C:xampphtdocs…’) #3 C:xampphtdocsgayatree-admin-panelsystemAutoloaderAutoloader.php(228): CodeIgniterAutoloaderAutoloader->loadInNamespace(‘CodeIgniterSes…’) #4 C:xampphtdocsgayatree-admin-panelsystemConfigServices.php(706): CodeIgniterAutoloaderAutoloader->loadClass(‘CodeIgniterSes…’) #5 C:xampphtdocsgayatree-admin-panelsystemConfigBaseService.php(100): CodeIgniterConfigServices::session(Object(ConfigApp), false) #6 C:xampphtdocsgayatree-admin-panelsystemConfigServices.php(699): CodeIgniterConfigBaseService::getSharedInstance(‘session’, NULL) #7 C:xampphtdocsgayatree-admin-panelsystemConfigBaseService.php(171): CodeIgniterConfigServices::session() #8 C:xampphtdocsgayatree-admin-panelsystemCommon.php(999): CodeIgniterConfigBaseService::__callStatic(‘session’, Array) #9 C:xampphtdocsgayatree-admin-panelappFiltersAuth.php(12): session() #10 C:xampphtdocsgayatree-admin-panelsystemFiltersFilters.php(181): AppFiltersAuth->before(Object(CodeIgniterHTTPIncomingRequest), NULL) #11 C:xampphtdocsgayatree-admin-panelsystemCodeIgniter.php(403): CodeIgniterFiltersFilters->run(‘/’, ‘before’) #12 C:xampphtdocsgayatree-admin-panelsystemCodeIgniter.php(333): CodeIgniterCodeIgniter->handleRequest(NULL, Object(ConfigCache), false) #13 C:xampphtdocsgayatree-admin-panelpublicindex.php(44): CodeIgniterCodeIgniter->run() #14 {main} in C:xampphtdocsgayatree-admin-panelsystemSessionHandlersFileHandler.php on line 21

i tried using string|false but not solved error

Docker (compose) nginx and php-fpm – how to set user permissions for mounted files

I have this basic setup for a webserver using php-fpm and nginx. Now, the files are in a given path and I want the files to be editable by the main user but also by the webserver.

Right now, files created by the webserver are listed as “root:root” and I do also not want to change folder permissions to 777, that is not secure. What is the best practice here?

There is a lot on the internet but I cannot find a concrete answer to this problem.

./docker-compose.yml:

services:
    # nginx
    web:
        image: nginx:latest
        ports:
            - "8003:80"
        volumes:
            - /mnt/samba_share_webserver:/var/www/html
            - ./nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf
    app:
        build:
            dockerfile: ./php/Dockerfile
        volumes:
            - /mnt/samba_share_webserver:/var/www/html

./php/Dockerfile:

FROM php:8.1-fpm-alpine

RUN docker-php-ext-install pdo pdo_mysql

./nginx/conf.d/default.conf

server {
    listen 80;
    server_name _ localhost;
    root /var/www/html;
    index index.php;

    location ~ .php$ {
       fastcgi_pass   app:9000;
       fastcgi_index  index.php;
       fastcgi_param REQUEST_METHOD $request_method;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       include        fastcgi_params;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
}

As you can see, the location where the files are stored are placed on a samba share running in another docker container. Those files need to be able to be altered by users making a smb connection.

I’m kind of experimenting and learning about permissions and how to use them. Could anyone give me a direction in for this problem?