Problem with the modal not appearing, only backdrop appears [closed]

I’m still a novice programmer. This is my modal; I’ve tried a lot of different approaches, but it simply shows the background. I tried manually on the console as well, but it didn’t work. This modal aim is to update the customer’s information.

<!-- Modal Edit Bahagian -->
            <div class="modal fade" id="modal-edit-bahagian" tabindex="-1" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 class="modal-title">Edit Bahagian</h4>
                        </div>
                        <div class="modal-body">
                            <form id="formEditBahagian" method="post">
                                <input type="hidden" id="nama_pemohon" name="nama_pemohon">
                                
                                <div class="form-group">
                                    <label for="edit-kategori-permohon" style="font-weight: bold;">Kategori Pemohon</label>
                                    <select id="edit-kategori-permohon" name="edit-kategori-permohon" required="required" class="form-control">
                                        <option value="">- Sila Pilih -</option>
                                        <option value="Jabatan Negeri">Jabatan Negeri</option>
                                        <option value="Jabatan Persekutuan">Jabatan Perseketuan</option>
                                        <option value="Sekolah-sekolah">Sekolah-sekolah</option>
                                        <option value="Swasta">Swasta</option>
                                        <option value="NGO">NGO</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-6">                  
                                            <label for="edit-gelaran-ketua-jabatan">Gelaran Ketua Jabatan</label>                       
                                            <input class="form-control" type="text" id="edit-gelaran-ketua-jabatan" name="edit-gelaran-ketua-jabatan" required>
                                            <small id="edit-gelaranError" style="display:none; color:red;"></small>
                                        </div>
                                        <div class="col-md-6">                  
                                            <label for="edit-agensi">Agensi</label>                     
                                            <input class="form-control" type="text" id="edit-agensi" name="edit-agensi" required>
                                            <small id="edit-agensiError" style="display:none; color:red;"></small>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-6">                  
                                            <label for="edit-bahagian">Bahagian</label>                     
                                            <input class="form-control" type="text" id="edit-bahagian" name="edit-bahagian" required>
                                            <small id="edit-bahagianError" style="display:none; color:red;"></small>
                                        </div>
                                        <div class="col-md-6">                  
                                            <label for="edit-nama-ketua-jabatan">Nama Ketua Jabatan</label>                     
                                            <input class="form-control" type="text" id="edit-nama-ketua-jabatan" name="edit-nama-ketua-jabatan" required>
                                            <small id="edit-namaketuaError" style="display:none; color:red;"></small>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="edit-alamat">Alamat Penuh</label>
                                    <textarea id="edit-alamat" name="edit-alamat" class="form-control" rows="3" required></textarea>
                                </div>

                                <div class="form-group">
                                    <label for="edit-nama-pemohon">Nama Pemohon</label>                     
                                    <input class="form-control" type="text" id="edit-nama-pemohon" name="edit-nama-pemohon" required>
                                    <small id="edit-namapemohonError" style="display:none; color:red;"></small>
                                </div>

                                <div class="form-group">
                                    <label for="edit-jawatan-pemohon">Jawatan Pemohon</label>                       
                                    <input class="form-control" type="text" id="edit-jawatan-pemohon" name="edit-jawatan-pemohon" required>
                                    <small id="edit-jawatanError" style="display:none; color:red;"></small>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-6">                  
                                            <label for="edit-tel-pejabat">No. Telefon Pejabat</label>
                                            <small style="font-size:13px; color: blue; font-style: italic;">*(Format: 03-61365652)</small>
                                            <input class="form-control" type="tel" id="edit-tel-pejabat" name="edit-tel-pejabat" required>
                                            <small id="edit-telpejabatError" style="display:none; color:red;"></small>
                                        </div>
                                        <div class="col-md-6">                  
                                            <label for="edit-tel-pengguna">No. Telefon Bimbit</label>
                                            <small style="font-size:13px; color: blue; font-style: italic;">*(Format: 012-70442695)</small>
                                            <input class="form-control" type="tel" id="edit-tel-pengguna" name="edit-tel-pengguna" required>
                                            <small id="edit-telpengunaError" style="display:none; color:red;"></small>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="edit-email">Email</label>
                                    <small style="font-size:13px; color: blue; font-style: italic;">*(Format: [email protected])</small>
                                    <input class="form-control" type="email" id="edit-email" name="edit-email" required>
                                    <small id="edit-emailError" style="display:none; color:red;"></small>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Tutup</button>
                            <button type="submit" form="formEditBahagian" class="btn btn-primary">Simpan</button>
                        </div>
                    </div>
                </div>
            </div>

Below here is the javascript that makes the modal appears but it didn’t. Can you guys please check the problem here. I think the problem lies on how i did the javascript.

<script>
                        // Log out functionality
                        $("#sign-out").click(function() {
                            $.ajax({
                                url: "proc_files/proc-logout.php",
                                success: function(result) {
                                    window.location.href = '../../';
                                }
                            });
                        });

                        $(document).ready(function() {
                            
                            // Initialize DataTable
                            $('#tbl_bahagian_selenggara').DataTable();
                            
                            // Debug click handler
                            $(document).on('click', '[onclick^="papar_tindakan_edit_bahagian"]', function() {
                                console.log('Edit button clicked');
                            });
                        });

                        function papar_tindakan_edit_bahagian(nama_pemohon) {
                            console.log('Function called with nama_pemohon:', nama_pemohon);
                            
                            // First show the modal
                            $('#modal-edit-bahagian').modal({
                                backdrop: 'static',
                                keyboard: false,
                                show: true
                            });
                            
                            // Then fetch the data
                            $.ajax({
                                url: 'bahagian_details.php',
                                type: 'POST',
                                data: { nama_pemohon: nama_pemohon },
                                dataType: 'json',
                                success: function(data) {
                                    if (data.error) {
                                        alert('Error: ' + data.error);
                                        return;
                                    }
                                    
                                    // Populate the form fields
                                    $('#nama_pemohon').val(data.nama_pemohon);
                                    $('#edit-kategori-permohon').val(data.kategori_permohon);
                                    $('#edit-bahagian').val(data.bahagian);
                                    $('#edit-gelaran-ketua-jabatan').val(data.gelaran_ketua_jabatan);
                                    $('#edit-agensi').val(data.agensi);
                                    $('#edit-nama-ketua-jabatan').val(data.nama_ketua_jabatan);
                                    $('#edit-alamat').val(data.alamat_pengguna);
                                    $('#edit-nama-pemohon').val(data.nama_pemohon);
                                    $('#edit-nokp-pemohon').val(data.nokp_pemohon);
                                    $('#edit-jawatan-pemohon').val(data.jawatan_pemohon);
                                    $('#edit-tel-pejabat').val(data.tel_pejabat);
                                    $('#edit-tel-pengguna').val(data.tel_pengguna);
                                    $('#edit-no-faks').val(data.no_faks);
                                    $('#edit-email').val(data.email_pengguna);
                                },
                                error: function(xhr, status, error) {
                                    console.log('XHR:', xhr.responseText);
                                    console.log('Status:', status);
                                    console.log('Error:', error);
                                    alert('Error fetching details. Please check the console for more information.');
                                }
                            });
                        }

                        

                        function tambah_tempahan(x) {
                            $("#modal-tambah-tempahan").modal('show');
                        }

                        
                        // Form submission handling
                        document.getElementById('formTempahan').onsubmit = function(event) {
                            event.preventDefault();

                            // Reset all error messages
                            resetErrorMessage('gelaranError');
                            resetErrorMessage('agensiError');
                            resetErrorMessage('namaketuaError');
                            resetErrorMessage('namapermohonError');
                            resetErrorMessage('kataError');
                            resetErrorMessage('kpError');
                            resetErrorMessage('jawatanpemohonError');
                            resetErrorMessage('telbimbitError');
                            resetErrorMessage('telpejabatError');
                            resetErrorMessage('emailError');
                            resetErrorMessage('faksError');

                            let hasError = false;

                            // Password validation
                            const password = document.getElementById('kata-laluan').value;
                            const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[W_]).{12,20}$/;

                            if (!password || !passwordRegex.test(password)) {
                                showError('kataError', '*Katalaluan mesti mengandungi sekurang-kurangnya 1 huruf besar, 1 huruf kecil, 1 nombor, 1 simbol dan panjang 12-20 karakter!');
                                hasError = true;
                            }

                            // Validation for text-only fields (no numbers)
                            const textOnlyFields = [
                                { id: 'gelaran-ketua-jabatan', error: 'gelaranError', label: 'Gelaran Ketua Jabatan' },
                                { id: 'agensi', error: 'agensiError', label: 'Agensi' },
                                { id: 'nama-ketua-jabatan', error: 'namaketuaError', label: 'Nama Ketua Jabatan' },
                                { id: 'bahagian', error: 'bahagianError', label: 'Bahagian' }
                            ];

                            const textOnlyRegex = /^[a-zA-Zs-.'()]+$/;

                            textOnlyFields.forEach(field => {
                                const input = document.getElementById(field.id);
                                if (input) {
                                    const value = input.value.trim();
                                    if (!value || !textOnlyRegex.test(value)) {
                                        showError(field.error, `*${field.label} hanya boleh mengandungi huruf sahaja!`);
                                        hasError = true;
                                    }
                                }
                            });

                            // Kad Pengenalan validation
                            const nokppermohon = document.getElementById('no-nokp-permohon').value.trim();
                            const nokppermohonRegex = /^d{12}$/; // Ensure exactly 12 digits

                            if (!nokppermohon || !nokppermohonRegex.test(nokppermohon)) {
                                showError('kpError', '*Nombor kad pengenalan permohon hanya mengandungi angka dan 12 digit sahaja!');
                                hasError = true;
                            }

                            // Nama validation
                            const namapermohon = document.getElementById('nama-permohon').value;
                            const namapermohonRegex = /^[a-zA-Zs]*$/;

                            if (!namapermohon || !namapermohonRegex.test(namapermohon)) {
                                showError('namapermohonError', '*Nama permohon hanya boleh mengandungi huruf sahaja!');
                                hasError = true;
                            }

                            // Email validation
                            const email = document.getElementById('email').value;
                            const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;

                            if (!email || !emailRegex.test(email)) {
                                showError('emailError', '*Format email yang dimasukkan adalah salah!');
                                hasError = true;
                            }

                            // Jawatan validation
                            const jawatanpermohon = document.getElementById('jawatan-permohon').value;
                            const jawatanpermohonRegex = /^[a-zA-Zs]*$/;

                            if (!jawatanpermohon || !jawatanpermohonRegex.test(jawatanpermohon)) {
                                showError('jawatanpemohonError', '*Jawatan hanya boleh mengandungi huruf sahaja!');
                                hasError = true;
                            }

                            // Phone number validation (Mobile)
                            const telefonbimbit = document.getElementById('no-telefonbim').value.trim();
                            const telefonbimbitRegex = /^d{3}-d{7}$/;

                            if (!telefonbimbit || !telefonbimbitRegex.test(telefonbimbit)) {
                                showError('telbimbitError', '*Format telefon bimbit tidak sah. Gunakan format: 012-7044269');
                                hasError = true;
                            }

                            // Phone number validation (Office)
                            const telefonpej = document.getElementById('no-telefonpej').value.trim();
                            const telefonpejRegex = /^d{3}-d{7}$/;

                            if (!telefonpej || !telefonpejRegex.test(telefonpej)) {
                                showError('telpejabatError', '*Format telefon pejabat tidak sah. Gunakan format: 012-7044269');
                                hasError = true;
                            }

                            // Faks validation
                            const nofaks = document.getElementById('no-faksimili').value.trim();
                            const nofaksRegex = /^d{2}-d{7}$/;

                            if (!nofaks || !nofaksRegex.test(nofaks)) {
                                showError('faksError', '*Format faksimili tidak sah. Gunakan format: 02-7044269');
                                hasError = true;
                            }

                            
                            // If validation passes, submit form via AJAX
                            if (!hasError) {
                                // Show confirmation modal
                                $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('show');
                                
                                // Handle confirmation button click
                                $("#btnSetuju").off('click').on('click', function() {
                                    

                                    // Show loading overlay
                                    $.LoadingOverlay("show");

                                    // Get form data
                                    const formData = new FormData(document.getElementById('formTempahan'));

                                    // Submit form via AJAX
                                    $.ajax({
                                        url: 'Php-files-admin/insert_bahagian_pendaftaran.php',
                                        type: 'POST',
                                        data: formData,
                                        processData: false,
                                        contentType: false,
                                        dataType: 'json',
                                        success: function(response) {
                                            if (response.success) {
                                                // Hide confirmation modal
                                                $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                                // Show success message
                                                $('#msg-berjaya').modal('show');
                                                // Close form modal
                                                $('#modal-tambah-tempahan').modal('hide');
                                                // Reload page after short delay
                                                setTimeout(function() {
                                                    location.reload();
                                                }, 1500);
                                            } else {
                                                // Hide confirmation modal
                                                $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                                // Show error message
                                                $('#text-tidak-berjaya').text(response.message || 'Maklumat tidak berjaya disimpan.');
                                                $('#msg-tidak-berjaya').modal('show');
                                            }
                                        },
                                        error: function(xhr, status, error) {
                                            // Hide confirmation modal
                                            $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                            // Show error message
                                            $('#text-tidak-berjaya').text('Error: ' + error);
                                            $('#msg-tidak-berjaya').modal('show');
                                        },
                                        complete: function() {
                                            // Hide loading overlay
                                            $.LoadingOverlay("hide");
                                        }
                                    });
                                });

                                // Handle cancel button click
                                $("#btnTidakSetuju").off('click').on('click', function() {
                                    $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                });
                            }
                        };

                        // Character counter for textarea
                        const alamatTextarea = document.getElementById('alamat');
                        const charCount = document.getElementById('charCount');
                        const maxLength = 150;

                        alamatTextarea.addEventListener('input', function() {
                            const currentLength = this.value.length;
                            const remaining = maxLength - currentLength;

                            charCount.textContent = remaining + ' characters remaining'

                            if (remaining <= 0) {
                                this.value = this.value.substring(0, maxLength);
                                charCount.textContent = '0 characters remaining';
                            }
                        });

                        // Helper function to reset error messages
                        function resetErrorMessage(elementId) {
                            const element = document.getElementById(elementId);
                            element.textContent = '';
                            element.style.display = 'none';
                        }

                        // Helper function to display error messages
                        function showError(elementId, message) {
                            const element = document.getElementById(elementId);
                            element.textContent = message;
                            element.style.display = 'block';
                        }

                          // Get the input elements
                            const nokpInput = document.getElementById('no-nokp-permohon');
                            const idPenggunaInput = document.getElementById('id-pengguna');

                            // Add event listener for input changes
                            nokpInput.addEventListener('input', function() {
                            // Copy the value from nokp to id pengguna
                            idPenggunaInput.value = this.value;

                            // Disable the id pengguna input
                            idPenggunaInput.readOnly = true;
                            });

                            // Initialize on page load
                            window.addEventListener('load', function() {
                            // Disable the id pengguna input if nokp has a value
                            if (nokpInput.value) {
                                idPenggunaInput.value = nokpInput.value;
                                idPenggunaInput.readOnly = true;
                            }
                            });

                    </script>

And down here is the php files

<?php
session_start();
include 'security/connection.php'; 

header('Content-Type: application/json');

if (!isset($_POST['nama_pemohon'])) {
    echo json_encode(['error' => 'nama_pemohon is required']);
    exit;
}

$nama_pemohon = $_POST['nama_pemohon'];

// Add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check connection first
if (!$conn) {
    echo json_encode(['error' => 'Database connection failed: ' . mysqli_connect_error()]);
    exit;
}

// SQL query to select data
$sql = "SELECT 
    kategori_permohon, 
    bahagian, 
    gelaran_ketua_jabatan, 
    agensi, 
    nama_ketua_jabatan, 
    alamat_pengguna, 
    nama_pemohon, 
    nokp_pemohon, 
    jawatan_pemohon, 
    tel_pejabat, 
    tel_pengguna, 
    no_faks, 
    email_pengguna 
    FROM db_tempahan_pdi.daftar_pengguna 
    WHERE status_bahagian = '1' 
    AND nama_pemohon = ?";

// Use prepared statement
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
    echo json_encode(['error' => 'Query preparation failed: ' . mysqli_error($conn)]);
    exit;
}

// Bind parameters
mysqli_stmt_bind_param($stmt, "s", $nama_pemohon);

// Execute the statement
if (!mysqli_stmt_execute($stmt)) {
    echo json_encode(['error' => 'Query execution failed: ' . mysqli_stmt_error($stmt)]);
    exit;
}

// Get the result
$result = mysqli_stmt_get_result($stmt);
if (!$result) {
    echo json_encode(['error' => 'Failed to get result: ' . mysqli_error($conn)]);
    exit;
}

$row = mysqli_fetch_assoc($result);

if ($row) {
    echo json_encode($row);
} else {
    echo json_encode(['error' => 'No data found for nama_pemohon: ' . $nama_pemohon]);
}

mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

Please help me on solving this issue

How to display percentages (not raw numbers) in a Doughnut chart using Chart.js and PHP?

I’m working on a project where I need to generate a Doughnut chart displaying the percentage distribution of different emotions based on data stored in a CSV file. I’m using PHP to parse the CSV and Chart.js to create the chart. However, I’m currently having two main issues:

The percentages are not showing up, even though I’m calculating them in JavaScript using Chart.js and the chart is properly rendered.
The total percentage adds up to over 100%.
Here’s a breakdown of what I’ve done so far:

PHP part: I’m using PHP to parse the CSV file and count the occurrences of different emotions. I then pass the emotion labels and their counts to JavaScript.
Chart.js part: I’m using the Chart.js datalabels plugin to try to show percentages on the chart.

Here’s my PHP code to read the CSV and count the occurrences of each emotion:

<?php
$data = array_map('str_getcsv', file('data_export.csv'));
array_shift($data);  // Skip header if present

$emotion_map = [
    'Excitement' => 1,
    'Inspiration' => 2,
    'Joy' => 3,
    'Curiosity' => 4,
    'Pride' => 5,
    'Hope' => 6,
    'Stress' => 7,
    'Panic' => 8,
    'Relief' => 9,
    'Confusion' => 10,
    'Boredom' => 11,
    'Disappointment' => 12,
];

$emotion_count = array_fill_keys(array_keys($emotion_map), 0);

foreach ($data as $row) {
    $emotion = trim($row[0]);
    if (isset($emotion_map[$emotion])) {
        $emotion_count[$emotion]++;
    }
}
?>

And here’s my JavaScript code for generating the Doughnut chart:

const doughnutCtx = document.getElementById('emotionDoughnutChart').getContext('2d');

const emotionLabels = <?php echo json_encode(array_keys($emotion_count)); ?>;
const emotionCounts = <?php echo json_encode(array_values($emotion_count)); ?>;

// Calculate the total count
const totalCount = emotionCounts.reduce((sum, count) => sum + count, 0);

const doughnutChart = new Chart(doughnutCtx, {
    type: 'doughnut',
    data: {
        labels: emotionLabels,
        datasets: [{
            label: 'Emotion Distribution',
            data: emotionCounts,
            backgroundColor: [
                '#1E90FF', '#FF7F50', '#FFE4B5', '#8BC34A', '#32CD32', '#4CAF50', '#D3D3D3',
                '#DC143B', '#8BC34A', '#7FFFD4', '#DDA0DD', '#D8BFD8'
            ],
            hoverOffset: 5
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false, 
        plugins: {
            legend: {
                display: true,
                position: 'top',
                labels: { font: { size: 10 } }
            },
            title: { display: true, text: 'Emotion Distribution' },
            datalabels: {
                color: 'white',
                formatter: function(value, context) {
                    let percentage = (value / totalCount * 100).toFixed(2);
                    return `${percentage}%`;  // Display percentage
                },
                font: { weight: 'bold', size: 14 }
            }
        },
        layout: { padding: { top: 10, bottom: 10 } }
    }
});

I have tried sing the chartjs-plugin-datalabels plugin to display the percentage but no luck .

Laravel 5.5 Job Queue Not Working In Parallel Despite Having Many Workers

I’m using Laravel 5.5 with the database queue driver to manage jobs, and I have 5 workers running. However, I’ve noticed that the rate at which jobs are processed remains constant at 100 jobs per minute, regardless of the number of workers.

When I tested locally, I found that the workers are processing jobs sequentially. A worker only starts processing a new job once the current one is finished, which eliminates the advantage of having multiple workers.

Previously, I encountered a similar issue when jobs in a custom queue were being processed sequentially. Switching back to the default queue resolved the problem, allowing jobs to be processed in parallel. However, even with all jobs in the default queue now, they are still being processed sequentially.

ENV File

QUEUE_DRIVER = database

Supervisord

[program:laravel_queue]
process_name=%(program_name)s_%(process_num)02d
command=php artisan queue:work --delay=10 --tries=10 --timeout=300
directory=/var/www/html
stdout_logfile=/var/www/html/storage/logs/laravel-queue.log
logfile_maxbytes=0
logfile_backups=0
redirect_stderr=true
autostart=true
numprocs=5
autorestart=true
startretries=86400

Apache CGI dir problem when trying to combining with PHP

I’m rather a rookie to the website development, and I have decided to make a website just for fun.

It’s a windows system.

I downloaded MySQL and have tabels built already.

I downloaded Apache and PHP.

Command php -v returns correct version info in ‘CMD’.

Address ‘http:localhost’ in browser returns correct greeting page that says “It works!!”.

=======================================

Informations above should proof a working Apache and PHP installation.

=======================================

The Apache has been binded with port 127.0.0.1:9000. (checked with netstat -ano | findstr :9000 and telnet 127.0.0.1)

File ‘php.ini’ has beed modified with extensions:

extension=mysqli 
extension=pdo_mysql

File ‘httpd.conf’ has modifications below:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so

<FilesMatch .php$>
    SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>

A test php file named ‘test.php’ that contains

<?php 
phpinfo(); 
?>

was put in folder ‘htdocs’.

But after I ran php-cgi.exe -b 127.0.0.1:9000 and httpd.exe in different CMD windows and input ‘localhost/test.php’ in my browser, I got error below:

Proxy Error
The proxy server could not handle the request
Reason: DNS lookup failure for: 127.0.0.1:9000d:

I assume the problem is the d: in the end, so that it cannot find the correct path to ‘test.php’

Did someone meet with this kind of problem before or know what is going on?

I would really appreciate your help, thank you !! ;).

The md5 hashing function in php is processed at different speeds on different servers [closed]

Good afternoon.

I have rented a VPS server and my website is running on it.
To increase the bandwidth, I decided to move to a more powerful server. (the characteristics are shown below)

The old server:
Characteristics of the old server

  • CPU: 4 core

  • RAM: 6GB

  • HDD: 165 GB

The new server:
Characteristics of the new server

  • CPU: 12 core

  • RAM: 24 GB

  • HDD: 295 GB

But as a result, I got that everything works 5 times slower on the new server.

Performed profiling on both servers using xdebug.

As a result of the analysis of the results, it turned out that the md5 function works in 2 ms on the old server, and in 10 ms on the new server.

Since this function is used in the process of localization of the site text into other languages, this feature slows down the loading of all countries by ~ 5 times

Below is the function in which the md5 function is called:

function __($key = ''){
        if(get_session('language')){
            $language = get_session('language');
        }else{
            if(!get_user("language")){
                $code = get_user("language");
                $language = db_get("*", TB_LANGUAGE_CATEGORY, ["code" => $code]);
                if(empty($language)){
                    $language = db_get("*", TB_LANGUAGE_CATEGORY, ["is_default" => 1]);
                }
            }else{
                $language = db_get("*", TB_LANGUAGE_CATEGORY, ["is_default" => 1]);
            }
            
            $language = json_encode($language);
            if(!empty($language)){
                set_session(["language" => $language]);
            }
        }

        if($language){
            $language = is_string($language)?json_decode( $language ):$language;

            if(isset($language->code)){
                $lang_file = WRITEPATH."lang/".$language->code.".json";
                if(file_exists($lang_file)){
                    $data = file_get_contents(WRITEPATH."lang/".$language->code.".json");
                    $data = json_decode($data, 1);
                    if(isset($data['data'])){
                        $data = $data['data'];
                        if($key != "" && isset($data[ md5($key) ])){
                            return $data[ md5($key) ];
                        }
                    }
                }
            }
        }

        return $key;
    }

The old server:

The new server:

QUESTION: The crux of the question is why the function runs 5 times slower on the new server (in 10 ms, versus 2 ms on the old server)

addition: The results in 2ms and 10ms are only for 1 function call. And there are more than 50 such calls when loading a page, which ultimately leads to a delay of 5 seconds for the user.

Ghostscript is not working with imagick error FailedToExecuteCommand

I have PHP Laravel script working with following configuration.

Laragon
Apache httpd-2.4.54-win64-VS16
PHP 8.3
Ghostscript 10.04.0
ImageMagick 7.1.0-18 Q16 x64

When I tried to convert pdf into image using exec command it works.

$pdfPath = $cvFile;
$outputPath = 'd:/temp/test.png';
$gsCommand = "gs -dNOPAUSE -dBATCH -sDEVICE=pngalpha -r144 -sOutputFile="$outputPath" "$pdfPath"";
exec($gsCommand, $output, $returnCode);

But it doesn’t works when I tried to convert pdf using Imagick().

$imagick = new Imagick();
$imagick->readImage($cvFile);

I got this error when I tried the execute the above code on line readImage().

FailedToExecuteCommand `”gs” -sstdout=%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 “-sDEVICE=pngalpha” -dTextAlphaBits=4 -dGraphicsAlphaBits=4 “-r72x72” -dPrinted=false “-sOutputFile=C:/Users/alish/AppData/Local/Temp/magick-fzsvjp49WgV_dLqdzA-KMiGFzpNpmnvQ%d” “-fC:/Users/alish/AppData/Local/Temp/magick-dC4PEbPqgCO7mlsy_cDaOIWgVTrR6Ixu” “-fC:/Users/alish/AppData/Local/Temp/magick-EJa1tcrtqJ9dcGUOrY2gv7–rqFtZS21″‘ (The system cannot find the file specified. ) @ error/delegate.c/ExternalDelegateCommand/516

Imagick should able to convert pdf into image using Ghostscript.

Get discount on first item only with coupon

I’m using woocommerce coupon. After using the “bcx” coupon code, every category (only just one not) make 50% discount. I want to make that gives customer a 50% discount on the first of each item on the cart. For example, customer buys 2 pcs of product A and 1 pcs of product B. The customer should get first item of product A and the product B the 50% discount. And important, that NOT using coupon code for one specific category). So it doesn’t matter how many pcs of each items you buy, the first one is always on 50% discount on each individual items. How can I solve this?

I tried with differnet plugins and it didn’t work.

Javascript suddenly not working on my WordPress Site [closed]

I am working my WP site with Git and because of that I have a local site, the same but on a Development Stage and again but for the Public and that’s the actual site ofc. Basically what is happening is that suddenly some Peepso (social network plugin) scripts stopped working and now the console tells me that some things are undefined. The thing is that this happens ONLY in the DEV Site, my local and public site are perfect, apart from an unique client that reported having the same issue, all people does not have any problem. Does anybody knows why is this happening or did you have a similar issue? Thanks in advance!
This is the dev site console:
enter image description here

This is the local site console (public site is basically the same) and those ‘left’ errors doesn’t cause problems:
enter image description here

I would like to understand what can cause those kind of problems and get to know how to solve it in the future.

filament via spatie laravel permissions

I’m using filament and spatie laravel permissions for roles(only for roles, it’s not my decision). When I’m trying to make Select in form like this:

Select::make('roles.name')
->relationship('roles', 'name')
->options(RoleType::class)
->required(),

I’m encountering the error:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: “writer” CONTEXT: unnamed portal parameter $3 = ‘…’ (Connection: pgsql, SQL: insert into “model_has_roles” (“model_id”, “model_type”, “role_id”) values (2, user, writer))
My enum:

enum RoleType: string implements HasLabel
{
    case Writer = 'writer';
    case User = 'user';

    public function getLabel(): ?string
    {
        return __('enums/role_type.' . $this->value);
    }
}

Also I’m using casts in Role model (via enum). I spent like 4 hours to solve this problem, but I can’t solve it. Also, when I’ve asked my mentor(I’m laravel intern) he said that I can’t use getStateUsing, options(list them all) e.t.c
Help me pls
P.S. php 8.3, laravel 11.30, filament 3.2, laravel-permission 6.10

I tried to use chatGPT to solve this problem, but he just used getStateUsing or options that I shouldn’t use.

How to force nginx wait for PHP-FPM processing

I am running a website that allows to import large Excel file. It is using PHP-FPM and Nginx. Nginx response 504 Gateway Time-out after exactly 60s. I have read many questions and try to change the configuration as following:

# Nginx
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
fastcgi_send_timeout 600s;
fastcgi_read_timeout 600s;
# PHP
request_terminate_timeout = 600s;
max_execution_time = 600s;

I need to ask Nginx response after 5 minutes or PHP-FPM finish processing the file. But it always response after 60 seconds and return 504 Gateway Time-out. I’ve tried to find where the configuration of PHP or Nginx involve to 60 seconds but nothing found.
Any idea?

JSON-based POST using jquery and AJAX [closed]

function update_row() {
  // Get the raw input from the request
  $raw_input = $this->input->raw_input_stream;
  log_message('info', 'Raw input: ' . $raw_input);

  // Decode the JSON input
  $data = json_decode($raw_input, true);

  // Check for JSON decode errors
  if (json_last_error() !== JSON_ERROR_NONE) {
      log_message('error', 'JSON decode error: ' . json_last_error_msg());
      echo json_encode(['status' => 'error', 'message' => 'Invalid JSON format']);
      return;
  }

  // Ensure data is an array and contains the necessary fields
  if (!is_array($data) || !isset($data['id'])) {
      log_message('error', 'Decoded data is not an array or missing ID. Data: ' . print_r($data, true));
      echo json_encode(['status' => 'error', 'message' => 'Missing ID']);
      return;
  }

  // Log the data for debugging
  log_message('info', 'Received data: ' . print_r($data, true));

  // Process and update the data
  $update_result = $this->Logistic_m->update_row($data);
  
  if ($update_result) {
      log_message('info', 'Row updated successfully');
      echo json_encode(['status' => 'success']);
  } else {
      log_message('error', 'Database update error');
      echo json_encode(['status' => 'error', 'message' => 'Database update error']);
  }
}

I try to save the row, but the frontend is updated successfully, but database not updated

PHP output started at php://input:1

In PHP I set a cookie using
setcookie($name, null, -1, '/');

However I get the following warning

Warning: Cannot modify header information - headers already sent by (output started at php://input:1)

which is even more strange, because I have ob_start() at the beginning of my PHP script.
I also set auto_prepend_file=NULL in my php.ini as described in Where could PHP output which started at php://input:1 be originating from?.

I use php-fpm 8.3 inside a Docker container, which is proxied by nginx.
As I understand it, php://input is a read only input stream, so where could the output be comming from?

How to turn off error types in VSCODE (PHP6606 for example) [closed]

In some inherited code, there are many cases where certain errors (such as PHP6606)

Constant from class 'subclass' referenced through child PHP(PHP6606)

appear due to the standards in place when the code was written. These mount up in the Find Problems (F8), making it difficult to find problems that really matter.

Using this as an example, is there a way to disable certain types of errors within VSCODE so that we can focus on real problems?

Use same shared memory unit from Lua and PHP

The closest I get in researching is stdin, stdout. But I don’t see how I can get it across two processes. I guess if I am running commands sequencially in the same terminal session, it could be done, but I do not see how to adapt that to my use case. I might be asking for the impossible which is why I haven’t found an answer.

I have a software that uses lua to parse data and can output json; I currently write that to a .json file.

Then a webpage, as .html or .php, running on localhost via a built-in php server (e.g. php -s localhost:8001) or what not, can read that .json file.

If I want the first program to be writing new output every second, that feels like excessive disc writing to burn out 86400 writes a day – somewhere in file size up to 30 kb in my higher end expectations. And the webpage keeps reading it repeatedly to get near realtime updates. Can I get this data transfer to be in RAM only between the two programs?

Maybe I am overthinking and it is moot as modern hardware will last decades even if being written over and over again every second. If that is the case, I can accept that answer and not worry about solving this cross-language cross-process puzzle.

I can only get stdin/out to work in the same terminal, e.g. in python (have not figured out lua stdin/out yet but should not be hard), and I can redirect that stdout into a file to then get the other program to access but I have no idea how to pass it directly to a webpage. Best bet is php I reckon.

This code doesn’t work. I set up a full fledged example based on the reading from comments by Robert who linked a lua and php discussion/documentation. Note, those are independent sources, so…

producer.lua

local shmem = require("shmem")
local mem = shmem.new(1024)
body = "some kind of test" 
mem:write(body) 

consumer.php

<?php 
$shm_id = shmop_open(0xff3,"c",0644,1024); 
if (!$shm_id) { echo "couldn't create shared memory segment`n"; } 
$shm_size = shmop_size($shm_id); 
$mystring = shmop_read($shm_id, 0, $shm_size); 
echo $mystring . "ipsum lorem" . $mystring 
shmop_close($shm_id); ?>  

And that is end of file. Of course the only thing output by php is ipsum lorem. I would have expected “some kind of testipsumloremsome kind of test”.