How to Allow Admin Users to Edit Formulas for Pricing Computation in Laravel/JS? [closed]

Please guide me to execute the following, I’m using JavaScript with Laravel:

  1. An admin role can CRUD a formula list that would appear in a dropdown option, for instance:

    • They can select from a list of products and its price would be retrieved.

    • The user can edit the formula by specifying whether
      (Item Price) - (input) + (input) % (input)
      etc.

  2. The formulas will be stored in dropdown that would affect the calculation of another form for final computation.

For instance in a sales form:

<h1>Sales Pricing Form</h1>

<form id="pricingForm">
    <!-- Dropdown for Formula Selection -->

    <label for="formulaDropdown">Select Formula</label>
    <select id="formulaDropdown" name="formula">
        <option value="avgFormula">Average Formula</option>
        <option value="saleFormula">Sale Formula</option>
    </select>
    <br><br>

    <!-- Input Fields -->
    <label for="quantity">Quantity</label>
    <input type="number" id="quantity" name="quantity" required>
    <br><br>

    <label for="totalAmount">Total Amount</label>
    <input type="number" id="totalAmount" name="totalAmount" required readonly>
    <br><br>

    <button type="submit">Submit</button>
</form>

The overall goal is when user clicks on a specific formula, it would affect the computation of the total amount.

I’m just currently brainstorming on how to best solve this problem. Thanks a lot!

PHP SoapClient using white spaces [duplicate]

The WSDL requires the following parameters:

<soapenv:Body>
  <cai3:Set> 
    <cai3:MOId>
            <gsm:param1>?</gsm:param1>
    </cai3:MOId>
    <cai3:MOAttributes>
      <gsm:setSubscription a="?">
        <gsm:custId>?</gsm:custId>
      </gsm:setSubscription>
    </cai3:MOAttributes>
  </cai3:Set>
</soapenv:Body>

Using this simple SOAP client call:

$params  = array(
        'MOId' => array
        (
          'param1' => "test1",
        ),
        'MOAttributes' => array 
        (
           'setSubscription a=123' => array 
            (
              'custId' => '123456'
            )
        )
);

$client = new SoapClient
        ($wsdl, 
        array(
            'location' => "http://$ip:8080/services/CAI3G1.2",
            'uri'      => "http://$ip:8080/services/CAI3G1.2",
            'exceptions' => true,
            'cache_wsdl' => WSDL_CACHE_NONE,   
            'connection_timeout' => 5,
            'trace'    => 1,
            'encoding'=>' UTF-8'
    ));    
try {
  $response = $client->Set($params);
} catch(Exception $e){
  if ($debug) print_r($e);
  return $e;
}

this is the following error:

[faultstring] => SOAP-ERROR: Encoding: object has no 'setSubscription' property

it seems like the white space in the XML parameter 'setSubscription a=123' is not accepted by the WSDL, is there an encoding issue here?

NOTE: if I put the same request on soapUI client, it works fine, here is my SOAPUI request XML:

  <soapenv:Body>
      <cai3:Set>
         <cai3:MOId>
            <gsm:param1>test1</gsm:param1>
         </cai3:MOId>
         <cai3:MOAttributes>
            <gsm:setSubscription a="123">
               <gsm:custId>123456</gsm:custId>
            </gsm:setSubscription>
         </cai3:MOAttributes>
      </cai3:Set>
   </soapenv:Body>




  

Weird PHP usort behavior when key is not present

Recently I’ve came into a weird behavior of PHP usort and I would like to share it and maybe get an explanation on why this is happening.

If you try to usort an array and the key used for sorting is not present in any of the array elements, the order is kept only until the array has less or equal to 16 elements. If the array has more than exactly 17 elements, the usort functions messes everything.

I’ve made a code so you can test it yourself on w3schools. https://www.w3schools.com/php/phptryit.asp?filename=tryphp_func_usort

<!DOCTYPE html>
<html>
<body>

<?php
   function my_sort($a, $b) {
     return (int)$a['sort_order'] - (int)$b['sort_order'];
   }
   
   //populating test array
   $array = array();
   for ($i=0; $i < 18; $i++) { 
    $array[$i] = array(
     'title' => $i
     );
   }

   foreach ($array as $key => $value) {
     echo $key . "=>".$value['title'];
     echo "<br>";
   }

    echo "<br>";
    echo "<br>";
    usort($array,"my_sort");

    foreach ($array as $key => $value) {
     echo $key . "=>".$value['title'];
     echo "<br>";
    }

     echo "<br>";
     echo "<br>";
     echo "<br>";
     echo "LESS THAN 17 Elements order is maintened";
     echo "<br>";
     echo "<br>";
     echo "<br>";

     $array = array();
     for ($i=0; $i < 16; $i++) { 
     $array[$i] = array(
      'title' => $i
     );
     }

     foreach ($array as $key => $value) {
       echo $key . "=>".$value['title'];
       echo "<br>";
     }

     echo "<br>";
     echo "<br>";
     usort($array,"my_sort");

     foreach ($array as $key => $value) {
      echo $key . "=>".$value['title'];
      echo "<br>";
     }
  ?> 

  </body>
  </html>

Is there any possible explanation for this behaviour?

Tested on PHP 7.3 and 8.4, same behavior

Uncaught Error: Unknown named parameter $value in AbstractLoader.php during Sylius installation in Docker [closed]

I am trying to install Sylius CE in a Docker environment following the official documentation. I am using the make init command to initialize the environment, but during the installation process, I encounter an error while clearing the cache:

// Clearing the cache for the dev environment with debug true                   
[1] [Config] INFO: Trigger value for 'XDEBUG_TRIGGER' not found, falling back to 'XDEBUG_SESSION'
[1] [Config] INFO: Trigger value for 'XDEBUG_SESSION' not found, so not activating
[20] CRITICAL  [php] Uncaught Error: Unknown named parameter $value ["exception" => Error { …}]
In AbstractLoader.php line 104:
Unknown named parameter $value

Additional Information:

  • Docker containers are running (including MySQL, PHP, Nginx, etc.).
  • PHP version in the container is 8.3.17.
  • I am using the Sylius-Standard image.
  • The error occurs during the cache clearing step.

Steps I have taken:

  • Clone project from official repository git clone [email protected]:Sylius/Sylius-Standard.git
  • Ran make init in the terminal to initialize the environment.
  • Installed all dependencies, but the error occurs during cache clearing.
  • The error message refers to the $value parameter in the AbstractLoader.php file.

What I have tried:

  • Updated the dependencies in the project using composer install.
  • Checked the PHP version in the container (PHP 8.3.17, which should be compatible).
  • Cleared the cache using php bin/console cache:clear.
  • Restarted Docker containers.

Additional Error Information:

The error points to an unknown $value parameter in a function in the AbstractLoader.php file. I couldn’t find a clear solution after researching.

Question:
Has anyone encountered a similar issue with Sylius and knows how to resolve it? What could be the cause of this error, and how can I fix it?

Fatal error: Uncaught ValueError: Path cannot be empty in PHP

I created a web application using PHP. In here I got an error while I am uploading images. I got this error on only some devices (mobile and pc). Please give me instructions to fix this.

Fatal error: Uncaught ValueError: Path cannot be empty in C:wamp64wwwBungalowSignupbackend.php on line 39
(!)ValueError: Path cannot be empty in C;lwamp64wwwBungalowSignupbackend.php on line 39

Line 39 is:

$check = getimagesize($_FILES["Picture"]["tmp_name"]);

Code below:

<?php
      include("Mysqlconnection.php");
      require 'PHPMailer/src/PHPMailer.php'; 
      require 'PHPMailer/src/SMTP.php';
      require 'PHPMailer/src/Exception.php';

      use PHPMailerPHPMailerPHPMailer;

    if (isset($_POST['submit'])) {
    $EmployeeID = $_POST['EmployeeID'];
    $Phone = $_POST['Phone'];
    $Password = $_POST['Password'];
    $cPassword = $_POST['cPassword'];

    $sql_executives = "SELECT Email, Name FROM executives WHERE EmployeeID='$EmployeeID'"; 
    $result_executives = mysqli_query($connection, $sql_executives);
    $count_executives = mysqli_num_rows($result_executives);

    if ($count_executives > 0) { // EmployeeID exists in executives table
        $row_executives = mysqli_fetch_assoc($result_executives);
        $Email = $row_executives['Email'];
        $Name = $row_executives['Name'];

        $sql_users = "SELECT * FROM users WHERE EmployeeID='$EmployeeID'";
        $result_users = mysqli_query($connection, $sql_users);
        $count_users = mysqli_num_rows($result_users);

        if ($count_users == 0) {
            if ($Password == $cPassword) {
                // Handle file upload
                $target_dir = "uploads/"; // Ensure this directory exists
                $file_name = basename($_FILES["Picture"]["name"]); // Get the file name
                $target_file = $target_dir . $file_name; // Full path for moving the file
                $uploadOk = 1;
                $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

                // Check if image file is an actual image or fake image
                $check = getimagesize($_FILES["Picture"]["tmp_name"]);
                if ($check !== false) {
                    // Check file size (e.g., limit to 5MB)
                    if ($_FILES["Picture"]["size"] > 5000000) {
                        echo '<script>alert("Sorry, your file is too large."); window.location.href="Signup.php";</script>';
                        $uploadOk = 0;
                    }
                } else {
                    echo '<script>alert("File is not an image."); window.location.href="Signup.php";</script>';
                    $uploadOk = 0;
                }

                // Allow certain file formats
                if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
                    echo '<script>alert("Sorry, only JPG, JPEG, PNG & GIF files are allowed."); window.location.href="Signup.php";</script>';
                    $uploadOk = 0;
                }

                // Check if $uploadOk is set to 0 by an error
                if ($uploadOk == 0) {
                    echo '<script>alert("Sorry, your file was not uploaded."); window.location.href="Signup.php";</script>';
                } else {
                    // Attempt to upload the file
                    if (move_uploaded_file($_FILES["Picture"]["tmp_name"], $target_file)) {
                        // Insert data into the users table, including only the file name
                        $sql_insert = "INSERT INTO users(EmployeeID, Name, Email, Phone, Password, Picture) VALUES('$EmployeeID', '$Name', '$Email', '$Phone', '$Password', '$file_name')";
                        $result_insert = mysqli_query($connection, $sql_insert);
                        if ($result_insert) {
                            // Send a success email to the user
                            $mail = new PHPMailer;
                            $mail->isSMTP();
                            $mail->Host = 'smtp.gmail.com';
                            $mail->SMTPAuth = true;
                            $mail->Username = '[email protected]';
                            $mail->Password = 'verw mhtt wikv itgm'; // Ensure this is secure in production
                            $mail->SMTPSecure = 'ssl';
                            $mail->Port = 465;

                            $mail->setFrom('[email protected]', 'Miriyakelle Bunglow');
                            $mail->addAddress($Email);

                            $mail->isHTML(true);
                            $mail->Subject = 'Bungalow Booking Account Created';
                            $mail->Body = "<h1>Account Created Successfully</h1>
                                           <p>Dear $Name,</p>
                                           <p>You have successfully created a Bungalow Booking account.</p>
                                           <p>Thank you for joining us!</p>";

                            if ($mail->send()) {
                                echo '<script>
                                        alert("Signup successful! Confirmation email sent.");
                                        window.location.href="Login.php";
                                      </script>';
                            } else {
                                echo '<script>
                                        alert("Signup successful, but failed to send confirmation email.");
                                        window.location.href="Login.php";
                                      </script>';
                            }
                        } else {
                            echo "Error: " . mysqli_error($connection);
                        }
                    } else {
                        echo '<script>alert("Sorry, there was an error uploading your file."); window.location.href="Signup.php";</script>';
                    }
                }
            } else {
                echo '<script>
                        window.location.href="Signup.php";
                        alert("Passwords do not match!");
                      </script>';
            }
        } else {
            echo '<script>
                    window.location.href="Signup.php";
                    alert("EmployeeID already exists!!");
                  </script>';
        }
    } else {
        echo '<script>
                window.location.href="Signup.php";
                alert("EmployeeID does not exist! Contact administrator or HR.");
              </script>';
    }
}
?>

I want help to fix this error.

I have this problem of undefined variable from the remote server, but this error does not occur on the local server. Can anyone help to solve it? [closed]

This is the error message:

ErrorException
Undefined variable $evento (View: /path/public_html/resources/views/admin/prelectores/index.blade.php)

This is function

class PreletorController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index($id)
    {
        
        $evento = Evento::find($id);
        $participantes = $evento->participantes()->where('participante_como','Prelector')->get();
        //dd($participantes[0]->preletor);
        return view('admin.prelectores.index', compact('participantes', 'evento'));
    }



Route::get('{id}/preletores/index', [PreletorController::class, 'index'])->name('prelector.index');

How to support unicode characters in a my mysqli based server [duplicate]

I have been tasked to add full unicode support inside our software.
We use Curl to send request to the server, and I am very new to php.
We want to support this type of email:
沙发模型@gmail.com
I tried to create accounts with that name and it fails for both gmail and outlook. But before dropping the feature i need to be 100% sure only utf-8 emails are allowed worldwide. So i want to support wide strings not just utf-8.

Our test database table look like this:
Database table

Here how an user is registered:

$result = mysqli_query($this->m_conn, "INSERT INTO ".self::TABLE_NAME."(EMAIL, LICENSE_KEYS, COMPUTER_CODES, IPS)  VALUES ('$email', '$license', 'null', 'null')");
if (!$result)
    Logger::ExitWithMessage($email, "DB: unable to insert user. SQL error:". mysqli_error($this->m_conn));

If i try to add a chinese user to our test table:

$robertoEmail = "roberto_沙发模型@hotmail.com";
$robertoLicense = "371C-5BE3-6EF4-9DBC-7F65";
        
$result = mysqli_query($this->m_conn, "INSERT INTO ".self::TABLE_NAME."(EMAIL, LICENSE_KEYS, COMPUTER_CODES, IPS)  VALUES ('$robertoEmail', '$robertoLicense', 'null', 'null')");
if (!$result)
    Logger::ExitWithMessage($robertoEmail, "DB: unable to insert user. SQL error:". mysqli_error($this->m_conn));

When I check the table, I get this “roberto_æ²™å‘æ¨¡åž‹@hotmail.com” as the email:
wrong table email

The email stored in the database is broken. But something strange i query the table with the roberto user(roberto_沙发模型@hotmail.com) it works:

$robertoEmail = "roberto_沙发模型@hotmail.com";

$query = mysqli_query($this->m_conn, "SELECT * FROM `". self::TABLE_NAME. "` WHERE EMAIL='$robertoEmail'");
if (!$query)
    Logger::ExitWithMessage($email, "DB: Can't select. SQL error:". mysqli_error($this->m_conn));

$user = mysqli_fetch_array($query);
mysqli_free_result($query);
    
if (!$user)
{
    error_log("GetUser failed");
    return;
}

// Everything worked!

Even more strange if i try to manually add roberto to the table:

    INSERT INTO `LICENSES_TABLE`(`EMAIL`, `LICENSE_KEYS`, `COMPUTER_CODES`, `IPS`) VALUES ('roberto_沙发模型@hotmail.com', '371C-5BE3-6EF4-9DBC-7F65', 'null', 'null')

I get this:
I get this

The email is reported as “[email protected]”.

How to properly support unicode emails in a mysqli based server?
Thanks!

While it is not relevant. Here how our C++ application send request to the server

RequestResult NetWork::sendRequest(const bool isPost, const std::string& relativeUri, const std::string& body) const
{
    CURL* handle = curl_easy_init();
    if (!handle)
        return RequestResult();

    /* First set the URL that is about to receive our POST. This URL can
     * just as well be a https:// URL if that is what should receive the
     * data.
     */
    curl_easy_setopt(handle, CURLOPT_URL, ("https://www.mywebsite.com/" + relativeUri).c_str());

    // Skip SSL verification.
    // Not required when server use a certificate signed by a trusted CA.
    // @See: https://stackoverflow.com/questions/56739554/is-https-without-ssl-verification-secure-for-local-application
    {
        /*
         * If you want to connect to a site who isn't using a certificate that is
         * signed by one of the certs in the CA bundle you have, you can skip the
         * verification of the server's certificate. This makes the connection
         * A LOT LESS SECURE.
         *
         * If you have a CA cert for the server stored someplace else than in the
         * default bundle, then the CURLOPT_CAPATH option might come handy for
         * you.
         */
        curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L);

        /*
         * If the site you're connecting to uses a different host name that what
         * they have mentioned in their server certificate's commonName (or
         * subjectAltName) fields, libcurl will refuse to connect. You can skip
         * this check, but this will make the connection less secure.
         */
        curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L);
    }

    // Specify the request type
    curl_easy_setopt(handle, CURLOPT_POST, (int)isPost);

    // Specify the body
    curl_easy_setopt(handle, CURLOPT_POSTFIELDS, body.c_str());

    // Specify the write callbaks
    RequestResult requestResult;
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, &requestResult.res);
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);

    // Perform the request
    const CURLcode res = curl_easy_perform(handle);
        
    // Check result
    if (res == CURLE_OK)
    {
        long http_code = 0;
        curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code);
        requestResult.success = http_code < 400;
    }
    else
    {
        _TRACE(requestResult.res);
    }

    // Cleanup
    curl_easy_cleanup(handle);

    return requestResult;
}

As you can see in the declaration the body is a std::string not a wide string. I dont know how it magically works but if email is (roberto_沙发模型@hotmail.com) then the sendRequest body contains (roberto_æ²™å‘æ¨¡åž‹@hotmail.com). The request is sent and the server understand that the real email is (roberto_沙发模型@hotmail.com)
request is sent

Scheduler completion regular task Moodle Stuck 3.6.2

moodle version 3.6.2, php 7.2 nts, Windows
I using task scheduler for running cron daily, when i check on moodle scheduledtasks
I notice the task completion_regular_task is stuck ( when i run on web it’s say Cannot obtain task lock ).
After deep searching, I notice when cron is running specially on
it’s stop and stuck there, I left for 24 hours and still stuck there, when i check on db mdl_lock_db task completion_regular_task is stuck and when I check on process db ssms


    Execute scheduled task: Calculate regular completion data (coretaskcompletion_regular_task)
    ... started 00:15:48. Current memory use 23.2MB.
    Starting course completion batch processing...
    >> Processed 0 records.
    >> Completion cron finished.

`

SELECT
    r.session_id AS VictimSession,
    r.blocking_session_id AS BlockingSession,
    r.wait_type,
    r.wait_time,
    r.last_wait_type,
    r.status,
    r.command,
    r.wait_resource,
    st.text AS RunningSQL
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) st
WHERE r.blocking_session_id <> 0;

`

VictimSession | BlockingSession | wait_type | wait_time | last_wait_type | status | command

52 | 52 | LCK_M_IX | 10768 | LCK_M_IX | suspended | UPDATE

  1. purge cache moodle
  2. delete file on moodledata (like cache, session, lock,temp)
  3. Debug on config moodle, show all error add some code like try and catch (to check if it’s work or not, the code is showing but it’s stuck again)
  4. check on log php and log moodle (got nothing, it’s not error)
  5. add index on table (maybe the data on db is too much)
  6. check on forum moodle (find nothing)

I though it’s because I using NFS and it’s locking (race condition), but even after I put moodledata on local server it’s still got same result, I only test cron on 1 server (other is shutdown, to make sure no double run cron)
my case is exactly same like this

This never happen before and usually after purgecache everything is back to normal.
Already stuck almost 2 weeks and still no clue for fixing this problem any idea?

Error exception on codeigniter 4 about open failed to open stream

error description

This error occurred when I uploaded an image file with the rules I wrote in the model. The image is still uploaded into a path that I have specified even though this error appears. AI said this error appears because codeIgniter doesn’t find the temporary file from your image upload. This is a typical error when the file has disappeared before being handled by the server.

protected $validationRules = [
        'image' => 'uploaded[image]|max_size[image,2048]|is_image[image]|mime_in[image,image/png,image/jpeg,image/jpg]',
    ];

controller code

in my controller, the way I check the validation for the uploaded file is like in the attached image. I hope to use validation from the model instead of writing it manually in the controller but written directly in the model.

multiple data doesnt deleted from table using Ajax in wordpress

I was define following script for deleting multiple data. Please check the attached image.enter image description here I will select multiple title and click deleted title button data will be deleted. I checked the log there is showing following error. I cant understand how to fix this error.

IDs received for deletion: Array
(
[0] => 10
1 => 8
)

check error: %d,%d
Prepared query for deletion: DELETE FROM wp_slf_schedule_post_title_log WHERE id IN (%d,%d)
IDs received for deletion: 0

PHP script

public function otslf_delete_multiple_blog_title() {

                //check_ajax_referer('ai-seo-content-nonce', 'nonce');
                if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ai-seo-content-nonce' ) ) {
                wp_send_json_error( __( 'Invalid nonce.', 'super-fast-blog-ai' ) );
                }   
                error_log( $_POST['nonce'] ); // Debugging line
            
                global $wpdb;
                $table_name = $wpdb->prefix . 'slf_schedule_post_title_log';
                $ids = isset($_POST['id']) ? array_map('intval', $_POST['id']) : [];


           error_log('IDs received for deletion: ' . print_r($ids, true)); // Debugging line
        
                $placeholders = implode(',', array_fill(0, count($ids), '%d'));
                $query = "DELETE FROM $table_name WHERE id IN ($placeholders)";

                error_log('check error: ' . $placeholders);                  // Debugging line
                error_log('Prepared query for deletion: ' . $query);         // Debugging line
                
                $deleted = $wpdb->query($wpdb->prepare($query, $ids)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery

                error_log('IDs received for deletion: ' . $deleted);

                if ($deleted !== false) {
                    wp_send_json_success(['message' => 'Selected titles deleted successfully.']);
                } else {
                    wp_send_json_error(['message' => 'Failed to delete selected titles.']);
                }
            }

jQuery script

jQuery(document).ready(function($) {
                        jQuery('#select_title').click(function() {
                            let isChecked = jQuery(this).is(':checked');
                            jQuery('input[name="select_title[]"]').prop('checked', isChecked);
                        });          
                        jQuery('#delete-selected').click(function(e) {
                            e.preventDefault();

                            let id = jQuery('input[name="select_title[]"]:checked').map(function() {
                                return jQuery(this).val();
                            }).get();

                            console.log('Selected IDs:', id);

                            if (id.length === 0) {
                                jQuery.toast({ text: "Please select at least one title to delete.", 
                                heading: 'Failed', 
                                icon: 'error',
                                showHideTransition: 'fade',
                                allowToastClose: true, 
                                hideAfter: 3000, 
                                stack: 5, 
                                position: 'top-right', 
                            });                        
                            }
                    
                            jQuery.ajax({
                                url: ajax_ob.ajax_url,
                                type: 'POST',
                                data: {
                                    action: 'otslf_delete_multiple_blog_title',
                                    id: id,
                                    nonce: ajax_ob.nonce
                                },
                                beforeSend: function(xhr) {
                                    jQuery('#delete-selected').append('<span class="loading-spinner"></span>');
                                },
                                success: function(response) {

                                    console.log('Response:', response);
                                    
                                    if (response.success) {
                                        jQuery('input[name="select_title[]"]:checked').closest('tr').remove();
                                        jQuery.toast({
                                            text: "!Selected Title Deleted Successfully",
                                            heading: 'success', 
                                            icon: 'success', 
                                            showHideTransition: 'fade', 
                                            allowToastClose: true, 
                                            hideAfter: 4000, 
                                            stack: 15, 
                                            position: { left : 'auto', right : 100, top : 153, bottom : 'auto' },
                                            textAlign: 'left',
                                            loader: true, 
                                            loaderBg: '#9EC600', 
                                        });
                                        
                                       /*  setTimeout(function() {
                                            location.reload();
                                        }, 2000); */ 

                                    } else {
                                        jQuery.toast({ text: "Please select at least one title to delete.", 
                                            heading: 'Failed', 
                                            icon: 'error',
                                            showHideTransition: 'fade',
                                            allowToastClose: true, 
                                            hideAfter: 3000, 
                                            stack: 5, 
                                            position: 'top-right', 
                                        });
                                    }
                                },
                            
                                complete: function() {
                                    jQuery('#delete-selected').find('.loading-spinner').remove();
                                },

                                error: function(xhr, status, error) {
                                    jQuery.toast({ text: 'An error occurred: ' + error, 
                                        heading: 'NOTE', 
                                        icon: 'error',
                                        showHideTransition: 'fade',
                                        allowToastClose: true, 
                                        hideAfter: 3000, 
                                        stack: 5, 
                                        position: 'top-right', 
                                    });
                                }
                            });
                        });
                    });

Fatal error: Uncaught ValueError: Path cannot be empty in PHP [closed]

I created a web application using PHP. In here i got a error while i am uploading images. I got this error on only some devices(mobile and pc). Error is mentioned in below. Please give me instructions to fix this.
Fatal error: Uncaught ValueError: Path cannot be empty in C:wamp64wwwBungalowSignupbackend.php on line 39
(!)ValueError: Path cannot be empty in C;lwamp64wwwBungalowSignupbackend.php on line 39

I want a help to fix this error.

Deploying filament 3 on laravel 12 returns 404

I’m trying to configure a debian 12 VPS to accept my locale project of filament 3.2 on laravel 12. I’ve installed mariadb, apache2 and php8.4. Locally everything works fine but online i got 404 for any route except main. On the VPS I have apache and that’s the .conf regarding the public root. I’ve copied the whole project into www/html directory

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
</Directory>

This is the 000-default.conf

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

If i go into the machine and print the php artisan route:list i got the correct list of route but when i go on them i got a 404. I can reach the / folder where i print a timestamp, i’ve tried to print there a route with the route command and it returns an empty string as laravel didn’t started.

I’ve tried to clean the cache and rebuilt it with no success

# Clear cache
php artisan optimize:clear

# Cache the various components of the Laravel application
php artisan config:cache
php artisan event:cache
php artisan route:cache
php artisan view:cache

Also a simple routing on web.php doesn’t work

Route::get('/test', function () {
    return 'Test route';
});

I’ve also tried to rebuild the symlink for storage since I saw other solved this way, but with no success

php artisan storage:link

What else should i check?

Symfony run process in background

I’m developing a small API for retrieving data based on OAuth 2 with PHP/Drupal/Symfony . This involves retrieving an access code, then retrieving a bearer token from this access code, and finally using this bearer token to retrieve user information. Everything works using a route on a controller, but I want this process to run in the background when the user is logged in to the site, meaning no manual interaction is required on a controller route. Here’s the code:

The controller :

namespace Drupalmy_moduleController;

use DrupalCoreControllerControllerBase;
use DrupalCoreRoutingTrustedRedirectResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentDependencyInjectionContainerInterface;

class OAuthController extends ControllerBase {

  protected $oauthClient;

  public function __construct($oauth_client) {
    $this->oauthClient = $oauth_client;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('my_module.oauth_client')
    );
  }

  /**
   * Initie le flux OAuth2
   */
  public function initiate() {
    $auth_url = $this->oauthClient->getAuthorizationUrl();
    return new TrustedRedirectResponse($auth_url);
  }

  /**
   * Callback après autorisation
   */
  public function callback(Request $request) {
    $code = $request->query->get('code');

    if (empty($code)) {
        $this->messenger()->addError($this->t('Authorization failed: no code received'));
        return $this->redirect('<front>');
    }

    // Échange le code contre un token
    $token = $this->oauthClient->getAccessToken($code);

    if (!$token || !isset($token['access_token'])) {
      $this->messenger()->addError($this->t('Failed to obtain access token'));
      return $this->redirect('<front>');
    }

    // Récupère les infos utilisateur
    $user_info = $this->oauthClient->getUserInfo($token['access_token']);
    dd($user_info);

    // Stocke le token en session
    $request->getSession()->set('oauth_userinfo', $user_info);

    // Redirige vers la page d'origine
    return $this->redirect('<front>');
  }

The route of the controller :

my_module.oauth_initiate:
  path: '/oauth/initiate'
  defaults:
    _controller: 'Drupalmy_moduleControllerOAuthController::initiate'
    _title: 'Initiate OAuth'
  requirements:
     _user_is_logged_in: 'TRUE'

my_module.oauth_callback:
  path: '/openid-connect/generic'
  defaults:
    _controller: 'Drupalmy_moduleControllerOAuthController::callback'
    _title: 'OAuth Callback'
  requirements:
     _user_is_logged_in: 'TRUE'

The service :

class OAuthClient {

  protected $httpClient;
  protected $openIdConfig;

  public function __construct(ClientFactory $http_client_factory, ConfigFactoryInterface $config_factory) {
    $this->httpClient = $http_client_factory->fromOptions([
      'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Accept' => 'application/json',
      ],
    ]);

    // Charge la configuration du client OpenID Connect "generic"
    $this->openIdConfig = $config_factory->get('openid_connect.client.generic');
  }

  /**
   * Génère l'URL d'autorisation OAuth2
   */
  public function getAuthorizationUrl() {
    $settings = $this->openIdConfig->get('settings');
    $params = [
      'response_type' => 'code',
      'client_id' => $settings['client_id'],
      'scope' => 'openid profile email',
      'redirect_uri' => $this->getRedirectUri(),
    ];
    return $settings['authorization_endpoint']. '?' . http_build_query($params);
  }



  /**
   * Échange le code contre un token
   */
  public function getAccessToken($code) {
    $settings = $this->openIdConfig->get('settings');
    try {
      $clientId = $settings['client_id'];
      $clientSecret = $settings['client_secret'];

      // Configuration complète de la requête
      $options = [
        'headers' => [
          'Content-Type' => 'application/x-www-form-urlencoded',
          'Authorization' => 'Basic ' . base64_encode($clientId . ':' . $clientSecret),
        ],
        'form_params' => [
          'grant_type' => 'authorization_code',
          'code' => $code,
          'redirect_uri' => $this->getRedirectUri(),
        ],
      ];

      $response = $this->httpClient->post($settings['token_endpoint'], $options);

      $body = $response->getBody()->getContents();

      Drupal::logger('oauth')->debug('Token response: ' . $body);

      return Json::decode($body);

    } catch (RequestException $e) {
      $errorDetails = [
        'message' => $e->getMessage(),
        'response' => $e->hasResponse() ? $e->getResponse()->getBody()->getContents() : null,
        'request' => [
          'url' => $e->getRequest()->getUri(),
          'headers' => $e->getRequest()->getHeaders(),
          'body' => $e->getRequest()->getBody()->getContents()
        ]
      ];

      Drupal::logger('oauth')->error('Token error details: @details',
        ['@details' => print_r($errorDetails, true)]
      );

      return FALSE;
    }
  }


/**
 * Récupère les infos utilisateur avec le token
 */
  public function getUserInfo($access_token) {
    try {
      $settings = $this->openIdConfig->get('settings');

      $response = $this->httpClient->get($settings['userinfo_endpoint'], [
        'headers' => [
          'Authorization' => 'Bearer ' . $access_token,
          'Accept' => 'application/json',
        ],
      ]);

      return Json::decode($response->getBody()->getContents());

    } catch (RequestException $e) {
      Drupal::logger('oauth')->error('UserInfo error: @error', [
        '@error' => $e->getMessage()
      ]);
      return FALSE;
    }
  }

in an eventSubscriber I tried to implement something like this but it won’t manage the access code

public function onUserLogin(AccountInterface $account) {
    $session = $this->requestStack->getCurrentRequest()->getSession();
    
    // Si déjà authentifié OAuth, ne rien faire
    if ($session->has('oauth_userinfo')) {
      return;
    }

    // 1. Initier le flux OAuth silencieusement
    try {
      $auth_url = $this->oauthClient->getAuthorizationUrl();

      
      // 2. Faire la requête directement (sans redirection navigateur)
      $client = Drupal::httpClient();
      $response = $client->get($auth_url, ['allow_redirects' => false]);

      // 3. Traiter la réponse
      if ($response->getStatusCode() == 302) {
        $location = $response->getHeader('Location')[0];
        dd($location);
        parse_str(parse_url($location, PHP_URL_QUERY), $params);

        if (!empty($params['code'])) {
          $token = $this->oauthClient->getAccessToken($params['code']);
          
          if ($token && isset($token['access_token'])) {
            $user_info = $this->oauthClient->getUserInfo($token['access_token']);
            $session->set('oauth_userinfo', $user_info);
          }
        }
      }
    } catch (Exception $e) {
      Drupal::logger('log_oauth')->error('Auto-auth failed: @error', ['@error' => $e->getMessage()]);
    }
  }

Thanks in advance for your help

JWT Cookie Removed After Page Refresh in React App (Frontend Localhost, Backend Server)

I’m developing a React app (http://localhost:5173) and a PHP backend hosted on a live server. I’m using JWT stored in an HttpOnly cookie for authentication.

When I log in, the backend sets the cookie successfully, and I can see it in Chrome DevTools → Application → Cookies. However, after I refresh the page, the cookie disappears completely, so the user gets logged out.

setcookie('token', $token, [
    'expires' => time() + 3600 * 24,
    'httponly' => true,
    'samesite' => 'Lax', 
    'secure' => false,
]);

header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: http://localhost:5173');      
header('Access-Control-Allow-Credentials: true');                
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

header('X-XSS-Protection: 1; mode=block');
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');

Why does the cookie get deleted on refresh in development? How can I persist the HttpOnly JWT cookie across page reloads when the frontend is local (localhost:5173) and the backend is hosted in the server?

Laravel 11 Events Firing Multiple Times in Production (Nginx, Azure App Services, PHP 8.3)

I’m encountering an issue where Laravel events are firing multiple times, but only in the production environment.

Environment:

  • Laravel: 11.x
  • PHP: 8.3
  • Web Server: Nginx
  • Hosting: Azure App Services
  • Setup:
    • One App Service runs the main Laravel application
    • A separate App Service handles scheduled tasks (cron)

We are dispatching Laravel events like this:

event(new ApplicationStatusChanged($application));

In production, these events trigger multiple times for a single operation. For example, a single POST request causes the event listener to run 2 times.

Check on direct GET request for Test and getting the same.

This does not happen in the local development environment.

We’re trying to understand:

  • Could this be due to Azure App Service architecture, deployment replication, or Nginx misconfiguration?
    • Why might synchronous Laravel events fire multiple times in a production setup like this?
  • Are there known quirks or debugging tips for this kind of behavior in Laravel 11/PHP 8.3?

We’ve ruled out:

  • Not using ShouldQueue on either the event or the listener — they are all synchronous.
  • Listeners are not making changes that could retrigger the event.
  • Confirmed it’s not job retries or queue-related (we’re not queuing).
  • No duplicate requests are hitting the endpoint.
  • Cache cleared completely (config, route, event, etc.).
  • Stopped the cron App Service entirely — issue still persisted