handle n+1 with hasManyThrough relation

my product has relation called values which is like this:

public function values()
{
    return $this->hasManyThrough(VariantValue::class, VariantProductOption::class, 'product_id', 'product_option_id');
}

everything works fine but when i have a multiple products in a single pages n+1 problem happens:

select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 61520 and `option_id` = 1
1.16ms
-----------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 81066 and `option_id` = 1
1.09ms
-----------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 81069 and `option_id` = 1
1.07ms
------------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 93662 and `option_id` = 1
1ms
-----------------------------------------
arya-lion
select `variant_sku_values`.*, `variant_sku_product_options`.`product_id` as `laravel_through_key` from `variant_sku_values` inner join `variant_sku_product_options` on `variant_sku_product_options`.`id` = `variant_sku_values`.`product_option_id` where `variant_sku_product_options`.`product_id` = 93724 and `option_id` = 1

i tried to eager load the values relation but this doesnt work.

php substring with n characters to left and right around searched keyword but don’t break the words

I’m building a custom search result in php where I want to return n characters from left and right of the searched keyword. I would also like to preserve whole words at the beginning and the end.

For example this is the text where I searched the keyword and I
need the text around it too.

So if I say n characters is 10 I would preferably get:

..searched the keyword and I need..

A simpler acceptable solution would be to break the words so the result would be:

..rched the keyword and I nee..

I started with this but got stuck on the string part before the keyword:

private function getSubstring($content,$keyword, $nOfChars) {
    $content = strtolower(strip_tags($content));
    $noOffoundStrings = substr_count($content, $keyword);
    $position = strpos($content, $keyword);
    $keywordLength = strlen($keyword);
    $afterKey = substr($content, $position + $keywordLength, $nOfChars);
    $beforeKey = substr($content, $position , -???); // how to get string part before the searched keyword
}

php gettext not working on wamp and windows 10

I know that this problem has been asked a dozens of times on here but I really looked at them all and tried everything but still no luck.

I’m trying to translate my app from french to english with PHP gettext. I’m parsing the gettext strings and store them in traduction.po to do the translation later with POEdit.
The problem is every single time it’s just outputing the original input.
 

My setup:

  • Windows 10 64-Bit french system locale
  • Wamp v3.3.1 64 bits
  • Apache 2.4.54.2
  • PHP 8.2.5

gettext setup code:

define('LOCALE_DIR', realpath($_SERVER['DOCUMENT_ROOT']). '/locale');

 

$locale = "en-US";
$domain = 'traduction';
putenv("LC_ALL={$locale}");
setlocale(LC_ALL, $locale);
bindtextdomain($domain, LOCALE_DIR);
textdomain($domain);
bind_textdomain_codeset($domain, 'UTF-8');
 
echo _("Bonjour");

Path to traduction:
C:wampwwwmyapplocaleen-USLC_MESSAGEStraduction.po

 
traduction.po

msgid ""
msgstr ""
"Project-Id-Version: Trad Project Anglaisn"
"POT-Creation-Date: 2023-04-14 14:54+0200n"
"PO-Revision-Date: 2023-04-14 14:54+0200n"
"Last-Translator: n"
"Language-Team: n"
"Language: en_USn"
"MIME-Version: 1.0n"
"Content-Type: text/plain; charset=UTF-8n"
"Content-Transfer-Encoding: 8bitn"
"Plural-Forms: nplurals=2; plural=(n != 1);n"
"X-Generator: Poedit 3.2.2n"
"X-Poedit-Basepath: ../../..n"
"X-Poedit-KeywordsList: _n"
"X-Poedit-SearchPath-0: .n"

 

#: index.php:17
msgid "Bonjour"
msgstr "Hello"

I’ve verified that gettext is enabled with phpinfo()

I also verified that the I got the right locals (since setlocale() returned false if the locale is en_US instead of en-US)

Here is the list of the installed locals in my Windows:

PS C:Usersme> Get-WinUserLanguageList

 


LanguageTag     : en-US
Autonym         : English (United States)
EnglishName     : English
LocalizedName   : Anglais (États-Unis)
ScriptName      : Latin
InputMethodTips : {0409:00020409}
Spellchecking   : True
Handwriting     : False

 

LanguageTag     : fr-FR
Autonym         : Français (France)
EnglishName     : French
LocalizedName   : Français (France)
ScriptName      : Latin
InputMethodTips : {040C:0000040C}
Spellchecking   : True
Handwriting     : False

Also I’m not sure if there’s one, but since I get no error message it would be nice if there’s a way that I can get a display of gettext’s log

Woocommerce: Change shipping class based on cart items shipping class count & free & flat_rate (mix of 3 shipping costs type)

I have 2 shipping classes.
One free shipping.
The other is 6 pieces for 1 piece shipping (id=43)

add_filter( 'woocommerce_package_rates', 'woocommerce_cool_rates' );
function woocommerce_cool_rates( $rates) {
  if ( ! WC()->cart->is_empty() ) {
    $class_cool = array(43);
    $found = false;
    $item_qty = 0;
    foreach( WC()->cart->get_cart() as $cart_item ){
      $item_shipping_class_id = $cart_item['data']->get_shipping_class_id();
      if( in_array( $item_shipping_class_id, $class_cool) ){
        $found = true;  /* Target shipping class found */
        $item_qty += $cart_item['quantity'];
        $item_quantity = floor(($item_qty + 5) / 6);
      }
    }
  }
  foreach ($rates as $rate_key => $rate) {
    if ($found) {
      $cool_cost = $rates[$rate_key]->cost;
      $new_cost = $cool_cost *   $item_quantity;
      $rates[$rate_key]->cost = $new_cost;
      $rates[$rate_key]->taxes = array();
      $rates[$rate_key]->set_taxes(0);
    }
}
return $rates;
}

This time, we have added a new shipping item.
It is a product of ‘flat_rate’.

However, with the above source, the quantity of the ‘flat_rate’ item cannot be calculated.
Therefore, I wrote the source as follows, but it does not work well.

add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates');
function woocommerce_package_rates( $rates) {
  if ( ! WC()->cart->is_empty() ) {
    $class_cool = array(43);
    $found = false;
    $item_qty = 0;
    foreach( WC()->cart->get_cart() as $cart_item ){
      $item_shipping_class_id = $cart_item['data']->get_shipping_class_id();
      if( in_array( $item_shipping_class_id, $class_cool) ){
        $found = true;  /* Target shipping class found */
        $item_qty += $cart_item['quantity'];
        $item_quantity =  floor(($item_qty + 5) / 6);
      }
    }

  }
  $total_shipping_cost = 0;
  foreach ($rates as $rate_key => $rate) {
    if ($rate->get_method_id() == 43) {
      $cool_cost = $rates[$rate_key]->cost;
      $new_cost = $cool_cost * $item_quantity;
      $rates[$rate_key]->cost = $new_cost;
    } elseif($rate->get_method_id() !== 43) { 
      $total_shipping_cost += $rate->get_cost();
    }
  }
return $rates;
}

Please let me know how this mix of 3 shipping costs works.

Request in destroy Controller

this problem killing me
I have store method and it work well and when create one, table update increase quantity correctly. but when I delete that Item which I’m created the table doesn’t update at all, and it most decrease the quantity

            $products = $request->items;

            for ($i = 0; $i < count($products); $i++) {
                $billProduct              = new BillProduct();
                $billProduct->bill_id     = $bill->id;
                $billProduct->product_id  = $products[$i]['item'];
                $billProduct->quantity    = $products[$i]['quantity'];
                
                $billProduct->save();

                Utility::total_quantity('plus',$billProduct->quantity,$billProduct->product_id);

and this is destroy controller

             if ($bill->created_by == Auth::user()->creatorId()) {
                $bill->delete();
                if ($bill->vender_id != 0) {
                    Utility::userBalance('vendor', $bill->vender_id, $bill->getTotal(), 'debit');
                }
               
                BillProduct::where('bill_id', '=', $bill->id)->delete();
                

and this is model which – or + quantity

Utility::total_quantity('plus',$billProduct->quantity,$billProduct->product_id);
Utility::total_quantity('munis',$billProduct->quantity,$billProduct->product_id);

how can I fix this problem in destroy??when I put the minus code in destroy methods get server error500.
thank you for help

Why does excel always gives me corrupted file every time i open the excel file that came from php

Why i can’t open the excel file that came from php.

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8");
header("Content-Disposition: attachment; filename="$filename"");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header('Cache-Control: private',false);
echo esc($exceldata);

I tried using that but it’s always say:

Excel cannot open the file ‘filename.xlsx’ because the file format or file extension is not valid. Verify that the file has not been curropted and that the file extension matches the format of the file.

I tried changing the the filename in xls but it doesn’t work in excel app in smartphone.

PHP program outputs the $response twice after the user has inputted their answer

the program that I’ve made has been bugging me for several days now and I really can’t fix it.
Here’s my code:

include 'generate_word.php';

if (!isset($_SESSION['chat_history']))
{
    $_SESSION['chat_history'] = array();
}

$num_words_generated = isset($_SESSION['num_words_generated']) ? $_SESSION['num_words_generated'] : 0;

if ($num_words_generated <= 10)
{
    $random_word_jumbled = str_shuffle($currentWord);
    $_SESSION['num_words_generated'] =+ $num_words_generated;
    $item_num = $_SESSION['num_words_generated'];

This is the one that’s been appearing twice

    $response = "<div id = 'output-container'><p>Question #" . $item_num . "<br>Unscramble the word: <strong>" . $random_word_jumbled . "</strong></p></div>";
    if (end($_SESSION['chat_history']) != $response)
    {
        array_push($_SESSION['chat_history'], $response);
    }
}else{

And this too

    $response = "<div id = 'output-container'><p>You have finished the quiz!<br>Go back to <a class = 'button' href = 'home.php'>home page.</a></p></div>";
    if (end($_SESSION['chat_history']) != $response)
    {
        array_push($_SESSION['chat_history'], $response);
    }
}

I’m hoping someone could give me some advice. Thanks in advance!

WordPress website redirecting to some anonymous links

My new WordPress website seems to be redirected to some anonymous links and i installed wordfence plugin and start scanning and there found some errors and those fixed also. But currently in wordfence scan my website is perfectly okay. But the redirecting issue still continues…is there any other way to finding out where the malicious files are hiding

need to find where the malicious files are present

Why can’t I assign values to my $_SESSION variables?

I have a problem that for some reason my $_SESSION variables seem to be empty when I am trying to echo them onto the form you can see on the picture. The name field (‘Név’ on the picture) works, however it is from another table from my database.

Here are the corresponding PHP code snippets:

personal.inc.php:

<?php
    session_start();
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    require_once 'dbh.inc.php';
    require_once 'getpersonal.inc.php';


    if (isset($_POST["submit_personal"])) {
        $birthdate = $_POST["birthdate"];
        $bio = $_POST["bio"];
        $dailyTime = $_POST["chintime"];
        $favChin = $_POST["favchin"];
        $ownsChinchilla = $_POST["owns_chinchilla"];
        $loveTime = $_POST["year_selector"];
        $userID = $_SESSION["id"];
        $new_name = $_POST["name"];

        $nameUp = "UPDATE user_form SET name='$new_name' WHERE id='$userID'";
        $conn->query($nameUp);

        $checker = "SELECT COUNT(*) FROM personal WHERE userID = '$userID'";
        $result = mysqli_query($conn, $checker);
        $row = mysqli_fetch_array($result);

        if ($row[0] > 0) {
            $stmt = $conn->prepare("UPDATE personal SET bio = ?, birthDate = ?, dailyTime = ?, loveTime = ?, favChin = ?, owner = ? WHERE userID = ?");
            $stmt->bind_param("ssssssi", $bio, $birthdate, $dailyTime, $loveTime, $favChin, $ownsChinchilla, $userID);
        } else {
            $stmt = $conn->prepare("INSERT INTO personal (userID, bio, birthDate, dailyTime, loveTime, favChin, owner) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("issssss", $userID, $bio, $birthdate, $dailyTime, $loveTime, $favChin, $ownsChinchilla);
        }

        getPersonal($conn);

        $stmt->execute();

        $stmt->close();
        $conn->close();
    }

    header("location: user.php");
    exit();
?>

getpersonal.inc.php:

<?php
    require_once 'dbh.inc.php';

    function dataExists($conn, $userID) {
        $sql = "SELECT * FROM personal WHERE userID = ?;";
        $stmt = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($stmt, $sql)) {
            header("location: login.php?error=stmtfailed");
            exit();
        }

        mysqli_stmt_bind_param($stmt, "s", $userID);
        mysqli_stmt_execute($stmt);

        $resultData = mysqli_stmt_get_result($stmt);

        if ($row = mysqli_fetch_assoc($resultData)) {
            return $row;
        } else {
            $result = false;
        }

        mysqli_stmt_close($stmt);
        return $result;
    }

    function getPersonal($conn) {
        $dataExists = dataExists($conn, $_SESSION["id"]);

        $_SESSION["bio"] = $dataExists["bio"];
        $_SESSION["favChin"] = $dataExists["favChin"];
        $_SESSION["owner"] = $dataExists["owner"];
        $_SESSION["birthDate"] = $dataExists["birthDate"];
        $_SESSION["dailyTime"] = $dataExists["dailyTime"];
        $_SESSION["loveTime"] = $dataExists["loveTime"];
    }
?>

HTML

<form method="post" action="personal.inc.php">
                <label>
                    <div class="namer">
                        <span class="identifier">Név:</span>
                        <input class="inner" type="text" name="name" placeholder="Itt módosíthatod a neved..." value="<?php echo $_SESSION["name"];?>">
                    </div>
                </label>
                <label>
                    <div class=dob>
                        <span class="identifier">Születési idő:</span>
                        <br>
                            <input class="inner" type="date" name="birthdate" value="<?php echo $_SESSION["birthDate"];?>">
                    </div>
                </label>
                <label>
                    <div class="bio">
                        <span class="identifier">Bio:</span>
                            <textarea class="inner" name="bio" width=400px height=230px placeholder="Mesélj magadról, hogy jobban megismerhessünk..." value="<?php echo $_SESSION['bio'];?>"></textarea>
                    </div>
                    
                </label>
                <label>
                    <div class=daily>
                        <span class="identifier">Napi csincsillával töltött idő:</span>
                        <br>
                        <select name="chintime" class="inner" value="<?php echo $_SESSION["dailyTime"];?>">
                            <option>Nincs csincsillám</option>
                            <option>Kevesebb, mint 1 óra</option>
                            <option>1-2 óra</option>
                            <option>3-5 óra</option>
                            <option>Több, mint 5 óra</option>
                        </select>
                    </div>
                </label>
                <label>
                    <div class="fav">
                        <span class="identifier">Kedvenc csincsilla a boltunkból:</span>
                        <div class=inner>
                            <select name="favchin" value="<?php echo $_SESSION["favChin"];?>">
                                <option>Mindet imádom!</option>
                                <option>Puffancs</option>
                                <option>Kókusz</option>
                                <option>Hamu</option>
                                <option>Nutella</option>
                                <option>Mochi</option>
                            </select>
                        </div>
                    </div>
                    
                </label>
                <label>
                    <div class="owner">
                        <span class="identifier">Van csincsillád?</span>
                        <div class=inner>
                            <select name="owns_chinchilla" value="<?php echo $_SESSION["owner"];?>">
                                <option>Nincs</option>
                                <option>Van</option>
                            </select>
                        </div>
                    </div>
                </label>
                <label>
                    <div class="longlove">
                        <span class="identifier">Mióta imádod a csincsillákat?</span>
                        <br>
                            <input class="inner" type="number" name="year_selector" id="year_selector" min="1900" max="2099" step="1" value="<?php echo $_SESSION["loveTime"];?>">
                    </div>
                </label>
                <button class="savebtn" type="submit" name="submit_personal"><i class="fa-solid fa-floppy-disk"></i><span>Mentés</span></button>
            </form>

This is what I expreience right now:
https://i.stack.imgur.com/tbHQI.png

I would like to echo the $_SESSION variables into my form when they are set in my database, so if the user only updates 1 field, the other fields won’t be touched.

Any form of help is appreciated,

Blaise

How to connect my custom web application to CoCCA registry?

I am a ccTLD registrar for (.af) domains. The CoCCA provided web portal for managing our domain is not responsive to our requirements. So I am recommended to build a completely new system from scratch using PHP(Laravel). At first I was expecting that its the matter of Rest API but later I understood there is another scenario (EPP). I did a lot of research in this regard but I am stack.
Form where to start?
How to start?
How to setup?
How to test?
Anyone who have worked in such projects and can cooperate I would be very thankful.

I learnt and gathered lots of information but I am not sure from where and how to start.
Why do I need a library?.
If I am not forced to use any specific library to build my custom system does every language like PHP will support EPP requests and protocols?.
I have been leaded that I can use the WHMCS module for CoCCA. I want to know what this module is for? benefit of using this module for me and If I do not want to use this module what is the next alternative.
So now I am in the development stage. Is there any test EPP server from CoCCA so that I can install it on my local computer. in the link (https://cocca.org.nz/srs/) there is an installation instructions. I am still confused as to why I need those installations.

Server Sent Events (SSE) StreamedResponse Blocks Requests in Laravel

I’ve implemented SSE in my Laravel application. It is working fine. But, it blocks the web application for the amount of time SSE is being executed.

public function index(Request $request)
{
    $response = new SymfonyComponentHttpFoundationStreamedResponse(function() use ($request) {
        while(true) {
            $data = $this->getData($request->currency);
            if ($data->hasChanged) {
                echo 'data: ' . json_encode($data->rates) . "nn";
                ob_flush();
                flush();
            }
            sleep(0.5);
        }
    });
    $response->headers->set('Content-Type', 'text/event-stream');
    $response->headers->set('X-Accel-Buffering', 'no');
    $response->headers->set('Cach-Control', 'no-cache');
    $response->headers->set('Access-Control-Allow-Origin', '*');
    return $response;
}

I have also tried session_write_close(); but it didn’t work.

Is there any solution to fix it in Laravel?

cakephp error Call to a member function where() on array

this is my code inside a view method , I’ve tried select and distinct but still got the same error

$uniqueViews = $this->Post->find()
    ->where(['Post.id' => $id])
    ->matching('Views', function ($q) {
        return $q->where(['Views.user_id IS NOT NULL']);
    })
    ->group(['Views.user_id', 'Post.id'])
    ->count();
    $this->set(compact('uniqueViews'));

and here is my view method

public function view($id = null) {
    // Get the user ID of the current user
    $user_id = $this->Auth->user('id');

    // Get the IP address of the current user
    $ip_address = $this->request->clientIp();

    // Find the post with the given ID
    $post = $this->Post->findById($id);

    // Increment the view count for the post, user ID, and IP address
    if ($post) {
        $this->Post->incrementViews($id, $ip_address, $user_id);
        $this->set('post', $post);
    } else {
        // Post not found
        $this->Flash->error(__('The post you requested could not be found.'));
        $this->redirect(array('action' => 'index'));
    }

    // Count the number of unique users that viewed the post
   

    $uniqueViews = $this->Post->find()
    ->where(['Post.id' => $id])
    ->matching('Views', function ($q) {
        return $q->where(['Views.user_id IS NOT NULL']);
    })
    ->group(['Views.user_id', 'Post.id'])
    ->count();
    $this->set(compact('uniqueViews'));


    // Throw an error if no ID is provided or the post is not found
    if (!$id || !$post) {
        throw new NotFoundException(__('Invalid post'));
    }
}

How to move functions from closures to normal functions

I’m trying to make a pest test file easier to read.

Currently, I’ve got some standard tests:

test('can get subscribers latest subscription', function () {
    /// function code here
});

test('can get subscribers active subscriptions', function () {
    /// function code here
});

But to then remind myself what tests I’ve written, I’ve got to scroll up and down the page over and over again.

What I’d like to do is change to something like the following:

test('can get subscribers latest subscription', getLatestSubscription());
test('can get subscribers active subscriptions', getActiveSubscriptions());

function getLatestSubscription() {
    /// function code here
});

function getActiveSubscriptions() {
    // function code here
});

However, the test functions include references to $this, which is available within the normal closure, but it’s not available in the standard function as I’ve set it up here.

Is there any way to get around this?