Some specific truncated strings are not matched via LIKE expression in SQL

I seem to not be able to debug it, there is a binary encoded BitTorrent info-hash string truncated to 20 bytes (Sha1), the length of string in db is 32 bytes (sha2), so I do LIKE expression this way:

if (strlen($info_hash) == 32) {
    $is_bt_v2 = true;
} elseif (strlen($info_hash) == 20) {
    $is_bt_v2 = false;
}
$info_hash = rtrim(DB()->escape($info_hash), ' ');

$info_hash_where = $is_bt_v2 ? "WHERE tor.info_hash_v2 = '$info_hash'" : "WHERE tor.info_hash = '$info_hash' OR tor.info_hash_v2 LIKE '$info_hash%'";

$sql = "
    SELECT tor.topic_id, tor.poster_id, tor.tor_type, tor.info_hash, tor.info_hash_v2, u.*
    FROM " . BB_BT_TORRENTS . " tor
    LEFT JOIN " . BB_BT_USERS . " u ON u.auth_key = '$passkey_sql'
    $info_hash_where
    LIMIT 1
";
$row = DB()->fetch_row($sql);

$is_bt_v2 is just a marker with checked length of hash string, so it will be true if hash length will be 32 bytes in the future (currently not supported by standard) and the search will be performed only in v2 column for performance, else it first will be checked in v1 then v2 via LIKE expression.

In reality hash is always truncated to 20 bytes even if it is sha2, so it is being checked in both columns (only the second condition in $info_hash_where).

The thing is, if I search full 32 bytes string it will return the result, somehow it works with other v2 strings truncated to 20 bytes, but some specific strings are not found.

I spent a week checking the db settings (MariaDb), but I don’t know what is happening.

Strings (v2):

Full: 97978479e7eba00af6f24953f6b94b229b556627167b710472ad4c9bc4ceac41 // Works

Truncated: 97978479e7eba00af6f24953f6b94b229b556627 // Works

Url encoded: %97%97%84y%e7%eb%a0%0a%f6%f2IS%f6%b9K%22%9bUf%27


Full: b5c69a98c0235cc2af0fa0c956a2984dc10410b1ab0eee46c9cb0c876d0c5189 // Works

Truncated: b5c69a98c0235cc2af0fa0c956a2984dc10410b1 // DOESN’T WORK!

Url encoded: %b5%c6%9a%98%c0%23%5c%c2%af%0f%a0%c9V%a2%98M%c1%04%10%b1

Im getting the issue while passing my dropdown fields into to the controller

This is my Blade code for handling the form like my requirement is need to get the guard from the guard table need to store data in the rounds table as well as i need to store selected checkpoints
from the dropdown in the db table ,the guard data is storing perfectly but the checkpoints data is not storing im getting the error like this rounds rounds
3 / 4 requests
3.8 kB / 3.8 kB transferred
{message: “The selected checkpoints must be an array.”,…}
errors
:
{selected_checkpoints: [“The selected checkpoints must be an array.”]}
message
:
“The selected checkpoints must be an array.”

{!! Form::open(['class'=>'form-horizontal ajax_form','method'=>'POST','files' => true, 'autocomplete' => 'off']) !!}
<div class="row">
    <!-- Left Column -->
        <div class="col-md-6 col-sm-6">
            <div class="portlet light bordered">
                   <!-- Title Start  -->
                    <div class="portlet-title">
                        <div class="caption font-purple-wisteria">
                            <i class="fa fa-user font-purple-wisteria"></i>{!! trans('Round Details') !!}
                        </div>
                    </div>
                    <!-- Title  -->

                    <!-- Body Start -->
                    <div class="portlet-body">
                        <!-- Add your left column form elements here -->
                            <div class="form-group">
                                <label class="col-md-3 control-label">{{ trans('Select Guard')}} <span class="required">* </span></label>
                                <div class="col-md-9">
                                    <select class="form-control" name="guard">
                                        @foreach ($guard as $guard)
                                            <option value="{{ $guard->id }}">{{ $guard->full_name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-md-3 control-label">{{ trans('RoundName')}}<span class="required">* </span></label>
                                <div class="col-md-9">
                                    <input type="text" class="form-control" name="roundname" id="roundname" placeholder="{{ trans('Roundname')}}" value="{{old('roundname')}}" disabled>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-md-3 control-label">{{ trans('StartTime')}}<span class="required">* </span></label>
                                <div class="col-md-9">
                                    <input type="time" class="form-control" name="shiftstartTime" id="shiftstartTime" placeholder="{{ trans('core.shiftstartTime')}}" value="{{old('shiftstartTime')}}" onchange="updateRoundName()">
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-md-3 control-label">{{ trans('EndTime')}}<span class="required">* </span></label>
                                <div class="col-md-9">
                                    <input type="time" class="form-control" name="shiftendTime" id="shiftendTime" placeholder="{{ trans('core.shiftendTime')}}" value="{{old('shiftendTime')}}" onchange="updateRoundName()">
                                </div>
                            </div>

                            <hr>
                            <button type="button" style="margin: 1% 0 1% 25%;" onclick="addEmployee();return false;" class=" btn green ">
                                {{ trans('core.btnSubmit')}}
                            </button>
                
                            <!-- Add more left column form elements as needed -->
                        
                    </div>
                    <!-- Body End -->
            </div>
        </div>

    
    <!-- Right Column -->
        <div class="col-md-6 col-sm-6">
                <div class="portlet light bordered">
                    <!-- Title Start -->
                    <div class="portlet-title">
                        <!-- Add your right column form elements here -->
                        <div class="caption font-purple-wisteria">
                            <i class="fa fa-user font-purple-wisteria"></i>{!! trans('Add Your checkPoint Here!') !!}
                        </div>
                    </div>
                    <!-- Title End -->

                    <!-- Body Start -->

                    <div class="portlet-body">
                        <!-- Add your right column form elements here -->
                        <div class="form-group">
                            <div class="col-md-10">
                              <label>{{ trans('Select Checkpoint')}} <span class="required">* </span></label>
                              <input type="hidden" name="selected_checkpoints[]" id="selected_checkpoints" value="">
                              <select class="form-control" name="selected_checkpoints[]" id="checkpoint-select">
                                @foreach ($checkpoint as $checkpoint)
                                    <option value="{{ $checkpoint->id }}">{{ $checkpoint->checkpointname }} {{ $checkpoint->id }}</option>
                                @endforeach
                            </select>


                                <button type="button" class="btn btn-success btn-sm" style="margin: 4% 14% 0% 0%;" id="add-checkpoint" onclick="addCheckpoint()">Add</button>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-12">
                                <table id="selected-checkpoints-table" class="table" style="background-color:#eff1f4;">
                                    <thead>
                                        <tr>
                                            <th>Sr.No.</th>
                                            <th>Checkpoint Name</th>
                                            <th>Delete</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Selected checkpoints will be displayed here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                    </div>
                    <!-- Body End -->

                </div>
        </div>
        <!-- Right column End -->
</div>
{!! Form::close() !!}

My js code

<script>
function addEmployee() {
    // Clear any previous error messages
    $('.form-group').removeClass('has-error');
    $('.help-block').remove();

    var isValid = true;

    // Validate Full Name
    var roundName = $('input[name="roundname"]').val().trim();
    if (roundName === '') {
        isValid = false;
        $('input[name="roundname"]').closest('.form-group').addClass('has-error');
        $('input[name="roundname"]').after('<span class="help-block">Round name is required.</span>');
    }

    if (isValid) {
        // Collect selected checkpoint IDs
        var selectedCheckpointIds = Array.from(document.querySelectorAll("#selected-checkpoints-table tbody tr")).map(function (row) {
            return row.dataset.checkpointId;
        });

        // Attach selectedCheckpointIds to the form data
        $('input[name="selected_checkpoints"]').remove(); // Remove any previous hidden input
        $('<input>').attr({
            type: 'hidden',
            name: 'selected_checkpoints',
            value: JSON.stringify(selectedCheckpointIds)
        }).appendTo('.ajax_form');

        // If all validations pass, proceed with form submission
        var url = "{{ route('admin.rounds.store') }}";
        $.easyAjax({
            type: 'POST',
            url: url,
            container: '.ajax_form',
            file: true,
        });
    }
}


// updating the roundname with the start time and endtime..
    function updateRoundName() {
        var startTime = document.getElementById('shiftstartTime').value.replace(':', ''); //it Remove colons
        var endTime = document.getElementById('shiftendTime').value.replace(':', ''); // Remove colons
        var roundnameField = document.getElementById('roundname'); // getting the roundname using the id..

        // Combine the start time and end time without colons
        var roundname = startTime + '-' + endTime;

        // Update the "roundname" field value
        roundnameField.value = roundname;
    }



// Checkpoint data
// Initialize an array to store selected checkpoint IDs
var selectedCheckpointIds = [];
var rowCount = 1; // Initialize rowCount to 1

// Function to add the selected checkpoint to the selected_checkpoints field
function addSelectedCheckpoint(checkpointId) {
    var selectedCheckpointsInput = document.getElementById("selected_checkpoints");
    var selectedCheckpoints = selectedCheckpointsInput.value ? selectedCheckpointsInput.value.split(",") : [];

    // Add the checkpointId to the selectedCheckpoints array
    selectedCheckpoints.push(checkpointId);

    // Update the selected_checkpoints field with the updated array
    selectedCheckpointsInput.value = selectedCheckpoints.join(",");
}

// Function to remove the selected checkpoint from the selectedCheckpointIds array
function removeSelectedCheckpoint(checkpointId) {
    var index = selectedCheckpointIds.indexOf(checkpointId);
    if (index !== -1) {
        selectedCheckpointIds.splice(index, 1);
    }
}

function addCheckpoint() {
    var selectBox = document.getElementById("checkpoint-select");
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;
    var selectedText = selectBox.options[selectBox.selectedIndex].text;

    if (selectedValue !== "") {
        // Check if the checkpoint has already been added
        var tableBody = document.querySelector("#selected-checkpoints-table tbody");
        var rows = tableBody.rows;
        for (var i = 0; i < rows.length; i++) {
            var existingValue = rows[i].cells[1].textContent;
            if (existingValue === selectedText) {
                alert("Checkpoint already added.");
                return;
            }
        }

        // Create a new row in the table and append it
        var newRow = tableBody.insertRow(tableBody.rows.length);
        newRow.insertCell(0).textContent = rowCount++; // Increment rowCount
        newRow.insertCell(1).textContent = selectedText;
        var deleteCell = newRow.insertCell(2);
        var deleteButton = document.createElement("button");
        deleteButton.textContent = "Delete";
        deleteButton.className = "btn btn-danger";
        deleteButton.onclick = function () {
            deleteRow(newRow);
            addOptionToSelect(selectedValue, selectedText);
            updateSno(); // Update the Sr.No.
            updateDropdownMessage(); // Update the dropdown message
            removeSelectedCheckpoint(selectedValue); // Remove this checkpoint from the selected_checkpoints field
        };
        deleteCell.appendChild(deleteButton);

        // Clear the selected option and remove it from the dropdown
        selectBox.remove(selectBox.selectedIndex);

        // Update the dropdown message
        updateDropdownMessage();

        // Add the selected checkpoint ID to the selectedCheckpointIds array
        selectedCheckpointIds.push(selectedValue);

        // Update the hidden input field with the selected checkpoint IDs
        document.getElementById("selected_checkpoints").value = selectedCheckpointIds.join(",");

        // Add the selected checkpoint ID to the selected_checkpoints field
        addSelectedCheckpoint(selectedValue);
    }
}




    function addOptionToSelect(value, text) {
        var selectBox = document.getElementById("checkpoint-select");
        var option = document.createElement("option");
        option.value = value;
        option.text = text;
        selectBox.appendChild(option);

        // Enable the dropdown when an option is added
        selectBox.disabled = false;

        // Update the dropdown message
        updateDropdownMessage();
    }

    function deleteRow(row) {
        var tableBody = document.querySelector("#selected-checkpoints-table tbody");
        tableBody.removeChild(row);
        updateSno(); // Update the Sr.No. after deletion

        // Enable the dropdown when a row is deleted
        var selectBox = document.getElementById("checkpoint-select");
        selectBox.disabled = false;

        // Update the dropdown message
        updateDropdownMessage();
    }

    function updateSno() {
        // Update the Sr.No. for all rows
        var tableBody = document.querySelector("#selected-checkpoints-table tbody");
        var rows = tableBody.rows;
        for (var i = 0; i < rows.length; i++) {
            rows[i].cells[0].textContent = i + 1;
        }
        rowCount = rows.length + 1; // Update the rowCount
    }


    function updateDropdownMessage() {
        var selectBox = document.getElementById("checkpoint-select");
        if (selectBox.options.length === 0) {
            selectBox.innerHTML = '<option value="">No checkpoints available</option>';
            selectBox.disabled = true;
        } else {
            // Remove the "No checkpoints available" option if it exists
            var noCheckpointOption = selectBox.querySelector('option[value=""]');
            if (noCheckpointOption) {
                selectBox.removeChild(noCheckpointOption);
            }
            selectBox.disabled = false;
        }
    }

my laravel code looks something like this

 public function store(Request $request)
{
    // Validate the form data
    $validatedData = $request->validate([
        'guard' => 'required',
        'shiftstartTime' => 'required',
        'shiftendTime' => 'required',
        'selected_checkpoints' => 'required|array', // Ensure selected_checkpoints is an array
        'selected_checkpoints.*' => 'exists:checkpoints,id', // Validate that each checkpoint exists in the "checkpoints" table
    ]);



    // Create a new round and save it
    $round = new Round();
    $round->guard_id = $validatedData['guard'];
    $round->shiftstartTime = $validatedData['shiftstartTime'];
    $round->shiftendTime = $validatedData['shiftendTime'];
    $round->save();

    // Attach selected checkpoints to the round
    $round->checkpoints()->attach($validatedData['selected_checkpoints']);

    // Redirect or return a response as needed

Errors

    im getting the error like this how to resolve this while except checkpoint field all my fields are storing in the db but the checkpointsdata is not storing
    Im getting the error like this  rounds  rounds  
    3 / 4 requests
    3.8 kB / 3.8 kB transferred
    {message: "The selected checkpoints must be an array.",…}
    errors
    : 
      {selected_checkpoints: ["The selected checkpoints must be an array."]}
message:"The selected checkpoints must be an array."

Dropzone Laravel 10

I’m trying to upload photos via Dropzone but when I try they don’t send. The function dd($request->file(‘file)) is not executed because file(‘file’) is null, and I don’t know why. Here is my script:

<script>
    Dropzone.options.fileUpload = {
        url: '{{route('admin.product.form')}}',
        addRemoveLinks: true,
        maxFilesize: 5,
        acceptedFiles: ".jpg, .jpeg, .png",
        dictRemoveFile: "Remove",
        accept: function(file) {
            let fileReader = new FileReader();

            fileReader.readAsDataURL(file);
            fileReader.onloadend = function() {

                let content = fileReader.result;
                $('#file').val(content);
                file.previewElement.classList.add("dz-success");
            }
            file.previewElement.classList.add("dz-complete");
        }
    }
</script>

Route:

Route::prefix('admin')->name('admin.')->middleware('admin')->group(function () {

    Route::get('/product', [ProductController::class, 'index'])->name('product');
    Route::post('/product', [ProductController::class, 'doProduct'])->name('product.form');
});

Controller:

  public function doProduct(Request $request)
    {

        if ($request->hasFile('file')) {
            $file = $request->file('file');
            dd($file);
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->storeAs('uploads', $filename); // Записване на файла в директория 'uploads'
        }


        echo 'hello';
    }

View:

 <div class="modal-body">
                <h5 class="modal-title">Variants</h5>
                <div class="mb-8">
                    <div class="dropzone dropzone-file-area" id="fileUpload">
                        <div class="dz-default dz-message">
                            <h3 class="sbold">Drop files here to upload</h3>
                            <span>You can also click to open file browser</span>
                        </div>
                    </div>
                </div>
            </div>

in using fpdf library i cannot get a cell content in next line in the same cell itried multicell also

in particulars column the content is not wrapping in the cell , it overlaps with next cell.
in using fpdf library i cannot get a cell content in next line in the same cell itried multicell also

foreach ($transactions as $transaction) {
        $formattedDate = date('d-m-Y', strtotime($transaction['date']));
        $cellWidth =80;
        $cellHeight =5;
        if ($pdf->GetStringWidth($transaction['particulars']) > $cellWidth) {
            $line = ceil($pdf->GetStringWidth($transaction['particulars']) / ($cellWidth - $errMargin));
        } else {
            $line = 10;
        }
 $description = '';
        $bill = '';
        $status = '';
    if ($transaction['particulars'] === 'Payment Received') {
        $description = 'Payment by';
        if (!empty($transaction['payment_type'])) {
            $description .=  " - " . $paymentTypeResult[0]['payment_type'] ;
            if (!empty($transaction['ref_no'])) {
                $description .= "n   Ref No: " . nl2br($transaction['ref_no']);
        }
        $description .=  $transaction['bill_no'] ;
        }
    } else {
        $description = $transaction['particulars'];

    }   

    if ($transaction['particulars'] === 'Sales' || $transaction['particulars'] === ' Return') { 
        $bill = $transaction['bill_no'];
    }
    else {
        $bill = '';
    }
    if ($transaction['payment_status'] === '2' && $transaction['particulars'] === 'Sales') {
        $status = 'Cleared';
    }
    else if($transaction['particulars'] === 'Sales' && $transaction['payment_status'] === null ) {
        $status = 'Pending';
    }

           $pdf->Cell(22, ($line * $cellHeight ), $formattedDate, 1);
           $pdf->Cell(20,($line * $cellHeight ), $bill, 1);
        
           
           $pdf->Cell(80,($line * $cellHeight ), $description, 1);

           $pdf->Cell(20, ($line * $cellHeight ), $transaction['debit'], 1);
           
           $pdf->Cell(20, ($line * $cellHeight ), $transaction['credit'], 1);
           $pdf->Cell(20, ($line * $cellHeight ), $status, 1);
           $pdf->Ln(); // Move to the next row

           $totalDebit += floatval($transaction['debit']);
           $totalCredit += floatval($transaction['credit']);
       }

cell content overlaps to next cell

text wrapping is not working pls help

in case of using multicell code in fpdf then the result is
enter image description here

Token request getting HTTP ERROR 500 , using API by PHP cURL

trying to using an API which calling by an external link and basic token authorization.
it has 3 steps like :
1- asking for token ( every half an hour)
2- pass the token to another combo box to getting result by bearer token
3- passing same bearer token to another combo box for fetching data .
everything works fine (getting token from POSTMAN) but the problem is starting when requesting php curl calling straightforward in the codes which gives me : HTTP ERROR 500 (have to refresh token request every half an hour)
here is the code:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
 CURLOPT_URL => 'https://api.rasatpa.ir/auth/oauth/token',
 CURLOPT_RETURNTRANSFER => true,
 CURLOPT_ENCODING => '',
 CURLOPT_MAXREDIRS => 10,
 CURLOPT_TIMEOUT => 0,
 CURLOPT_FOLLOWLOCATION => true,
 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
 CURLOPT_CUSTOMREQUEST => 'POST',
 CURLOPT_POSTFIELDS => array(,,),
 CURLOPT_HTTPHEADER => array(
   'Authorization: Basic YXRpeWVoSGNwV3M6QHRpeWUkd3NAdXNlcg=='
 ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>  

Symfony Doctrine :Column Not Added to Table in Database Despite Executing php bin/console doctrine:schema:update –complete –force Command

Column Not Added to Table in Database Despite Executing php bin/console doctrine:schema:update –complete –force Command

The command php bin/console doctrine:schema:update --force is indeed generating entities with fields. However, when I attempted to add a field to an existing entity, it didn’t work as expected. Despite the command being successful in creating initial entities and their fields, it seems to encounter issues when trying to modify existing entities by adding new fields. I’m facing difficulties in updating the schema with additional fields for pre-existing entities.

doctrine.yaml

doctrine:
    dbal:
        driver: pdo_mysql
        host: '%database_host%'
        port: '%database_port%'
        dbname: '%database_name%'
        user: '%database_user%'
        password: '%database_password%'
        # only needed for MySQL
        charset: utf8mb4
        default_table_options:
            collate: utf8mb4_unicode_ci
        mapping_types:
            enum: string
        server_version: 5.7
        # Pour changer le mode sql pour supporter le NONE_FULL_GROUP_BY pour les requêtes sql
        options:
            1002: 'SET sql_mode=(SELECT REPLACE(@@sql_mode, "ONLY_FULL_GROUP_BY", ""))'
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: '%kernel.project_dir%/var/data/data.sqlite'
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #path: '%database_path%'

    orm:    
        auto_generate_proxy_classes: false
        naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
        auto_mapping: true
        dql:
            string_functions:
                WEEK: DoctrineExtensionsQueryMysqlWeek
                MONTH: DoctrineExtensionsQueryMysqlMonth
                YEAR: DoctrineExtensionsQueryMysqlYear
            datetime_functions:
                TimestampDiff: DoctrineExtensionsQueryMysqlTimestampDiff
        mappings:
            App:
                is_bundle: false
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'AppEntity'
                alias: App

when@test:
    doctrine:
        dbal:
            # "TEST_TOKEN" is typically set by ParaTest
            dbname_suffix: '_test%env(default::TEST_TOKEN)%'

when@prod:
    doctrine:
        orm:
            auto_generate_proxy_classes: false
            query_cache_driver:
                type: pool
                pool: doctrine.system_cache_pool
            result_cache_driver:
                type: pool
                pool: doctrine.result_cache_pool

    framework:
        cache:
            pools:
                doctrine.result_cache_pool:
                    adapter: cache.app
                doctrine.system_cache_pool:
                    adapter: cache.system

entity:

<?php

namespace AppEntity;

use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineDBALTypesTypes;
use DoctrineORMMapping as ORM;

/**
 * Incident_collecte
 * 
 * @author Alaa
 *
 * @ORMTable(name="incident_collecte")
 * @ORMEntity(repositoryClass="AppRepositoryIncidentCollecteRepository")
 * 
 */
class IncidentCollecte
{
 ---------   
    /**
     * @ORMColumn(type="array", nullable=true)
     * 
     * Table des meta-données d'un incident qui permet sa gestion, comme son état précédent
     **/
    private $metaData;

    #[ORMColumn(type: Types::DATETIME_MUTABLE, nullable: true)]
    private ?DateTimeInterface $UpdatedDateStatutFromPortal = null;

/**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set dateCreation
     *
     * @param DateTime $dateCreation
     *
     * @return IncidentCollecte
     */
    public function setDateCreation($dateCreation)
    {
        $this->date_creation = $dateCreation;

        return $this;
    }

    /**
     * Get dateCreation
     *
     * @return DateTime
     */
    public function getDateCreation()
    {
        return $this->date_creation;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return IncidentCollecte
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set idDemande.
     *
     * @param int $idDemande
     *
     * @return IncidentCollecte
     */
    public function setIdDemande($idDemande)
    {
        $this->id_demande = $idDemande;

        return $this;
    }

    /**
     * Get idDemande.
     *
     * @return int
     */
    public function getIdDemande()
    {
        return $this->id_demande;
    }

    /**
     * Set dateCloture.
     *
     * @param DateTime|null $dateCloture
     *
     * @return IncidentCollecte
     */
    public function setDateCloture($dateCloture = null)
    {
        $this->date_cloture = $dateCloture;

        return $this;
    }

    /**
     * Get dateCloture.
     *
     * @return DateTime|null
     */
    public function getDateCloture()
    {
        return $this->date_cloture;
    }

    /**
     * Set typeDemande.
     *
     * @param string|null $typeDemande
     *
     * @return IncidentCollecte
     */
    public function setTypeDemande($typeDemande = null)
    {
        $this->type_demande = $typeDemande;

        return $this;
    }

    /**
     * Get typeDemande.
     *
     * @return string|null
     */
    public function getTypeDemande()
    {
        return $this->type_demande;
    }

    /**
     * Set cleDemande.
     *
     * @param string $cleDemande
     *
     * @return IncidentCollecte
     */
    public function setCleDemande($cleDemande)
    {
        $this->cle_demande = $cleDemande;

        return $this;
    }

    /**
     * Get cleDemande.
     *
     * @return string
     */
    public function getCleDemande()
    {
        return $this->cle_demande;
    }

    /**
     * Set raisonCloture.
     *
     * @param string|null $raisonCloture
     *
     * @return IncidentCollecte
     */
    public function setRaisonCloture($raisonCloture = null)
    {
        $this->raison_cloture = $raisonCloture;

        return $this;
    }

    /**
     * Get raisonCloture.
     *
     * @return string|null
     */
    public function getRaisonCloture()
    {
        return $this->raison_cloture;
    }

    /**
     * Set priorite.
     *
     * @param string $priorite
     *
     * @return IncidentCollecte
     */
    public function setPriorite($priorite)
    {
        $this->priorite = $priorite;

        return $this;
    }

    /**
     * Get priorite.
     *
     * @return string
     */
    public function getPriorite()
    {
        return $this->priorite;
    }

    /**
     * Set etat.
     *
     * @param string $etat
     *
     * @return IncidentCollecte
     */
    public function setEtat($etat)
    {
        $this->etat = $etat;

        return $this;
    }

    /**
     * Get etat.
     *
     * @return string
     */
    public function getEtat()
    {
        return $this->etat;
    }

    /**
     * Set regle.
     *
     * @param string|null $regle
     *
     * @return IncidentCollecte
     */
    public function setRegle($regle = null)
    {
        $this->regle = $regle;

        return $this;
    }

    /**
     * Get regle.
     *
     * @return string|null
     */
    public function getRegle()
    {
        return $this->regle;
    }

    /**
     * Set DatePriseEnCompteClient.
     *
     * @param DateTime|null $datePriseEnCompteClient
     *
     * @return IncidentCollecte
     */
    public function setDatePriseEnCompteClient($dateMajClient = null)
    {
        $this->date_prise_en_compte_client = $dateMajClient;

        return $this;
    }

    /**
     * Get DatePriseEnCompteClient.
     *
     * @return DateTime|null
     */
    public function getDatePriseEnCompteClient()
    {
        return $this->date_prise_en_compte_client;
    }

    /**
     * Set impact.
     *
     * @param string|null $impact
     *
     * @return IncidentCollecte
     */
    public function setImpact($impact = null)
    {
        $this->impact = $impact;

        return $this;
    }

    /**
     * Get impact.
     *
     * @return string|null
     */
    public function getImpact()
    {
        return $this->impact;
    }

    /**
     * @return Collection|Siiv[]
     */
    public function getSiiv(): Collection
    {
        return $this->siiv;
    }

    public function addSiiv(Siiv $siiv): self
    {
        if (!$this->siiv->contains($siiv)) {
            $this->siiv[] = $siiv;
        }

        return $this;
    }

    public function removeSiiv(Siiv $siiv): self
    {
        $this->siiv->removeElement($siiv);

        return $this;
    }

    /**
     * Set collecteurLogs.
     *
     * @param string|null $collecteurLogs
     *
     * @return IncidentCollecte
     */
    public function setCollecteurLogs($collecteurLogs = null)
    {
        $this->collecteur_logs = $collecteurLogs;

        return $this;
    }

    /**
     * Get collecteurLogs.
     *
     * @return string|null
     */
    public function getCollecteurLogs()
    {
        return $this->collecteur_logs;
    }

    /**
     * Set metaData.
     *
     * @param array|null $metaData
     *
     * @return IncidentCollecte
     */
    public function setMetaData($metaData = null)
    {
        $this->metaData = $metaData;

        return $this;
    }

    /**
     * Get metaData.
     *
     * @return array|null
     */
    public function getMetaData()
    {
        return $this->metaData;
    }

    /**
     * @return string|null
     */
    public function getNumoffense(): ?string
    {
        return $this->numoffense;
    }

    /**
     *
     * @param string|null $numoffense
     * @return IncidentCollecte
     */
    public function setNumoffense(?string $numoffense): IncidentCollecte
    {
        $this->numoffense = $numoffense;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getSeverity(): ?string
    {
        return $this->severity;
    }

    /**
     * @param string|null $severity
     * @return IncidentCollecte
     */
    public function setSeverity(?string $severity): IncidentCollecte
    {
        $this->severity = $severity;

        return $this;
    }

    public function getUpdatedDateStatutFromPortal(): ?DateTimeInterface
    {
        return $this->UpdatedDateStatutFromPortal;
    }

    public function setUpdatedDateStatutFromPortal(?DateTimeInterface $UpdatedDateStatutFromPortal): static
    {
        $this->UpdatedDateStatutFromPortal = $UpdatedDateStatutFromPortal;

        return $this;
    }
}

Docker Php and apache install Composer

I want to start project and make my own framework for technical future work test, so i want to install composer for install some library, but when i execut

docker-compose exec php bash

terminal say to me service “php” is not running

My question is : What is the right container for running composer ? apache, php ? Create a composer container ?

I have docker-compose.yml

version: "3.8"
services:
  apache:
    container_name: apache
    build: ./docker/apache
    links:
      - php
    ports:
      - "81:80"
    volumes:
      - ./src:/usr/local/apache2/htdocs
  php:
    container_name: php
    build: ./docker/php
    ports:
      - "9000:9000"
    volumes:
      - ./src:/usr/local/apache2/htdocs
    working_dir: /usr/local/apache2/htdocs

with Docker file for apache

// apache/Dockerfile

FROM httpd:2.4.51

COPY apache.conf /usr/local/apache2/conf/apache.conf

RUN echo "Include /usr/local/apache2/conf/apache.conf" 
    >> /usr/local/apache2/conf/httpd.conf

with apache.conf

LoadModule deflate_module /usr/local/apache2/modules/mod_deflate.so
LoadModule proxy_module /usr/local/apache2/modules/mod_proxy.so
LoadModule proxy_fcgi_module /usr/local/apache2/modules/mod_proxy_fcgi.so

<VirtualHost *:80>
    ProxyPassMatch ^/(.*.php(/.*)?)$ fcgi://php:9000/usr/local/apache2/htdocs/$1

    DocumentRoot /usr/local/apache2/htdocs

    <Directory /usr/local/apache2/htdocs>
        Options -Indexes +FollowSymLinks
        DirectoryIndex index.php
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

and DockerFile for PHP with COMPOSER installation

FROM php:8.1-fpm
WORKDIR /var/www

RUN apt-get update
RUN docker-php-ext-install pdo pdo_mysql mysqli

RUN apt-get install -y autoconf pkg-config libssl-dev
RUN pecl install mongodb
RUN echo "extension=mongodb.so" >> /usr/local/etc/php/conf.d/mongodb.ini

COPY --from=composer /usr/bin/composer /usr/bin/composer

Log in issue – PHP and HTML [closed]

php

html

enter image description here

I just started PHP and try to make simple project about log in below you can able to see code of HTML and also PHP, I also make data based I added data as well.

So the issue I face is basically when I enter the correct details I mean password it show me same message that your password is incorrectly and I don’t know the issue might be password_hash have issue not sure.

Data base HTML PHP

Data Based, I added the image of that data base one.

Username is 1234 and password is also 1234 not working at all could you please help out to fix that issue for me. Thank you so much.

I try everything I changed all the code but still not working and also I use default hash option that also not working. what I’m expecting that what is issue on this code or what causes that issue that if I even enter the correct details it show me incorrect password

HTML2PDF not handling display: none

I’m trying to use the HTML2PDF PHP library to generate a PDF starting from a complex HTML page. The PDF is being generated successfully, but the HTML elements of my source page that have style="display: none" are being displayed in the PDF. I need the elements that have display: none in the HTML to also be hidden in the PDF.

I thought that maybe HTML2PDF was failing to read the CSS class, so I moved the display: none to inline, but this did not solve the problem.

Then I thought maybe HTML2PDF couldn’t read inline stiles either, but when I changed the inline style to text-decoration: underline the text was actually underlined in the PDF!

Is it possible that the display CSS property is ignored?

How to fix PHP Image won’t load, and CSS won’t work

does anybody know how to fix this?
I’m using Xampp and Visual Studio Code, and when I try to link my CSS to PHP and run, only the html can be seen and the CSS won’t show up. Also, when I try to use and run, img won’t load. Please help me 🙁

I tried following steps in Youtube. But none of them work.

Here's the problem in image.

TCPDF and NOBR, struggling to make it work

I’m trying to produce a PDF using TCPDF, and generally speaking everything is fine. I am producing a list of vehicles, and a couple of lists of information about each vehicle. These are created in the form of individual HTML tables. This works as expected, but with the problem that page breaks can occur within a vehicle record – so I might get the header at the bottom of the page, and the other two tables on the next page.

I’ve done a bit of reading and found that there are two options, either to set the `page-break-inside: avoid’, or to add ‘nobr=true’. I’ve found that for these to work, I have to set K_TCPDF_CALLS_IN_HTML to be true, I have done that and if I echo that value, it is set to 1. I am aware that TCPDF only parses parameters which are set with ” quotes rather than ‘ quotes. I have tried both methods in a div surrounding each vehicle record, and each time it makes no difference, the div is just split across a page if required. I have tried removing the font changes in case that breaks the div, but it didn’t help.

Here is a summary of my code, the TCPDF stuff is all pretty much based on the first example from their web site:

<?php
include("my_database.php");

// Include the main TCPDF library (search for installation path).
require_once('vendor/tecnickcom/tcpdf/tcpdf.php');

// Get the model details
$model_id = $_POST['model_id'];
$q1 = "select model, make from car_models left join car_makes on car_models.make_id = car_makes.id where car_models.model_id = ?";
$prep = $dbc->prepare($q1);
$ex = $prep->execute(array($model_id));
$model = $prep->fetchAll();
if (count($model) > 0) {
    $mname = $model[0]['make'] . " " . $model[0]['model'];

    $query = "select car_id from cars where model_id = ? and (hidden <> 2) order by registration";
    $prep = $dbc->prepare($query);
    $ex = $prep->execute(array($model_id));
   if ($ex) {
    $cars = $prep->fetchAll();
    $vehcount = count($cars);

    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    
    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('My Name');
    $pdf->SetTitle('My vehicle List');
    $pdf->SetSubject('Vehicle List');
    $pdf->SetKeywords('cars, list');
    
    // set default header data
    $pdf->SetHeaderData("mylogo.png", 40, 'My vehicle Register', $mname . " - " . $vehcount . " recorded", array(0,64,255), array(0,64,128));
    $pdf->setFooterData(array(0,64,0), array(0,64,128));
    
    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    
    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    
    // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    
    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    
    // set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    
    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        $pdf->setLanguageArray($l);
        }
    
    // ---------------------------------------------------------
    
    // set default font subsetting mode
    $pdf->setFontSubsetting(true);
    
    // Add a page
    // This method has several options, check the source code documentation for more information.
    $pdf->AddPage();
    
    // I've tried both of these, without success.
    //$pbopen = "<div style="page-break-inside:avoid;">";
    $pbopen = "<div nobr="true">";
    $pbclose = "</div>";
    
    foreach($cars as $car) {
        $carinfo = getCarInfoAsHTML($dbc, $car['car_id']);
        
if (is_array($carinfo)) {
        $pdf->SetFont('helvetica', '', 14, '', true);

    $pdf->writeHTML($pbopen . $carinfo['header'], true, false, false, false, '');
    
    $pdf->SetFont('helvetica', '', 10, '', true);
    $pdf->writeHTML($carinfo['owner'], true, false, false, false, '');
    $pdf->writeHTML($carinfo['notes'], true, false, true, false, '');
    $pdf->writeHTML("<hr />" . $pbclose, true, false, true, false, '');
    
    
    // ---------------------------------------------------------
    
    // Close and output PDF document
    // This method has several options, check the source code documentation for more information.
    
    }
    else {
        echo "Car not found. ";
        }
    }
        $pdf->Output($mname . ".pdf", 'I');

}
}
else {
echo "Invalid model id";
}   

?>

I’ve taken out stuff that I think is irrelevant here, but I hope I’ve left enough in place to help someone see what I’m doing incorrectly. This is typical (but edited for privacy) of what each string returned will contain:

  'header' => string '<table cellspacing='0' cellpadding='1'><tr><td style="width: 30%">Registration</td><td style="width: 70%">ABC 123V </td></tr><tr><td>Date of Registration</td><td></td></tr><tr><td>Model</td><td>Ford Fiesta</td></tr><tr><td>VIN</td><td> / </td></tr><tr><td>Last VED / MOT / V5</td><td>SORN / Not recorded / </td></tr></table>' (length=334)
  'owner' => string '<h3>Owner Sequence</h3><table><tr><th style="width: 10%">&nbsp;</th><th style="width: 32%">Owner</th><th style="width: 20%">Area</th><th style="width: 18%">From</th><th>To</th></tr><tr><td>1</td><td>Bill Clinton</td><td>Northern Ireland</td><td></td><td></td></tr></table>' (length=279)
  'notes' => string '<h3>Notes</h3><table><tr><th style="width: 25%">Date</th><th style="width: 75%">Notes</th></tr><tr><td style="width:25%;">&nbsp;</td><td style="width: 75%">Rally car. </td></tr><tr><td style="width: 25%;">2023-03-20</td><td style="width: 75%">Last-taxed-date changed from '' to 'SORN'</td></tr></table>' (length=306)

My code should therefore create a separate <div> for each vehicle, inside which is one, two or three HTML tables (not all have a list of owners, or any notes). It works well, but it splits a vehicle record across a page break which I’d like to avoid. I’m sure I am missing something simple, but I can’t see what it is.

WooCommerce Configure the Product List Display

I am trying to figure out a way to display the information of the products differently but not to sort them on this matter.

Currently it is showing first product_name then product_price and last it shows product_stock.

I would want to show the information in this order instead product_name, product_stock and after product_price.

I added a code snippet to force the product_stock to appear on the product list page.

Do i need to do something similar to force the display the way i want or is this locked by woocommerce?

Thanks for any information

A redirection problem in my PHP proxy server for loading webpages

I have a proxy server written in PHP for a browser in a browser project, but when inside something like google.com and I tried doing a search inside the proxy server, it’s going to take me to “proxyserver/search?q=hi” instead of the expected result which is “proxyserver/proxy.php?url=https://google.com/search?q=hi”

Basically the main problem is if a site rendered inside the proxy server tried taking me from /pageone to /pagetwo, it takes me from “proxyserver/proxy.php?url=https://example.com/pageone” to “proxyserver/pagetwo”

I tried pretty much everything to fix this, but it for some reason wouldn’t work so I just reverted back to the old code that still has the bug.

Full code:

ob_start("ob_gzhandler");
ini_set('memory_limit', '128M');
session_start();

$cookieFile = 'cookies.txt';

if (!isset($_COOKIE['PHPSESSID'])) {
    clearCookies();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['url'])) {
    $url = $_GET['url'];
    proxyRequest($url);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['url'])) {
    $url = $_POST['url'];
    $postData = http_build_query($_POST);

    echo "Debug: POST URL - " . $url . "<br>";
    echo "Debug: POST Data - " . $postData . "<br>";

    if (isset($_GET['url'])) {
        $url = $_GET['url'];
        echo "Debug: Using GET URL - " . $url . "<br>";
    }

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        echo "Error: Invalid URL.";
        exit;
    }

    proxyRequest($url, $postData);
} else {
    echo "Debug: Invalid request received. ";
    echo "Debug: GET Data - " . json_encode($_GET) . "<br>";
    echo "Debug: POST Data - " . json_encode($_POST) . "<br>";

    echo "Error: Invalid request.";
}

function proxyRequest($url, $postData = null) {
    header('Content-Type: text/html');
    header('Access-Control-Allow-Origin: *');

    global $cookieFile;

    $customDNS = [
        'example.com:80:1.1.1.1',
        'example.com:443:8.8.8.8',
    ];

    $ch = curl_init($url);

    $options = [
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
        CURLOPT_HTTPHEADER => [
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Language: en-GB',
            'Accept-Encoding: gzip, deflate',
            'Dnt: 1',
            'Sec-GPC: 1',
            'Sec-Fetch-Dest: document',
            'Sec-Fetch-Mode: navigate',
            'Connection: keep-alive',
            'Upgrade-Insecure-Requests: 1',
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_AUTOREFERER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_RESOLVE => $customDNS,
    ];

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $options[CURLOPT_POST] = true;
        $options[CURLOPT_POSTFIELDS] = $postData;
    }

    if (isset($_COOKIE['PHPSESSID'])) {
        $options[CURLOPT_COOKIEJAR] = $cookieFile;
        $options[CURLOPT_COOKIEFILE] = $cookieFile;
    }

    curl_setopt_array($ch, $options);

    $content = curl_exec($ch);

    if ($content !== false) {
        preg_match_all('/Set-Cookie: (.*?);/i', $content, $matches);
        $receivedCookies = implode('; ', $matches[1]);

        file_put_contents($cookieFile, $receivedCookies);

        error_log('Received content: ' . $content);

        echo $content;
    } else {
        error_log('Error: Unable to fetch content from the external website. cURL Error: ' . curl_error($ch));

        echo "Error: Unable to fetch content from the external website. cURL Error: " . curl_error($ch);
    }

    curl_close($ch);
}

function clearCookies() {
    global $cookieFile;
    if (file_exists($cookieFile)) {
        unlink($cookieFile);
    }
}
?>

Changes in captcha image through coding

I use the following captcha code which works correctly:

<?php
session_start();
//You can customize your captcha settings here

$captcha_code = '';
$captcha_image_height = 50;
$captcha_image_width = 130;
$total_characters_on_image = 6;

//The characters that can be used in the CAPTCHA code.
//avoid all confusing characters and numbers (For example: l, 1 and i)
$possible_captcha_letters = 'bcdfghjkmnpqrstvwxyz23456789';
$captcha_font = './monofont.ttf';

$random_captcha_dots = 45;
$random_captcha_lines = 20;
$captcha_text_color = "0x021f64";
$captcha_noise_color = "0x021f64";


$count = 0;
while ($count < $total_characters_on_image) { 
$captcha_code .= substr(
    $possible_captcha_letters,
    mt_rand(0, strlen($possible_captcha_letters)-1),
    1);
$count++;
}

$captcha_font_size = $captcha_image_height * 0.65;
$captcha_image = @imagecreate(
    $captcha_image_width,
    $captcha_image_height
    );

/* setting the background, text and noise colours here */
$background_color = imagecolorallocate(
    $captcha_image,
    255,
    255,
    255
    );

$array_text_color = hextorgb($captcha_text_color);
$captcha_text_color = imagecolorallocate(
    $captcha_image,
    $array_text_color['red'],
    $array_text_color['green'],
    $array_text_color['blue']
    );

$array_noise_color = hextorgb($captcha_noise_color);
$image_noise_color = imagecolorallocate(
    $captcha_image,
    $array_noise_color['red'],
    $array_noise_color['green'],
    $array_noise_color['blue']
    );

/* Generate random dots in background of the captcha image */
for( $count=0; $count<$random_captcha_dots; $count++ ) {
imagefilledellipse(
    $captcha_image,
    mt_rand(0,$captcha_image_width),
    mt_rand(0,$captcha_image_height),
    2,
    3,
    $image_noise_color
    );
}

/* Generate random lines in background of the captcha image */
for( $count=0; $count<$random_captcha_lines; $count++ ) {
imageline(
    $captcha_image,
    mt_rand(0,$captcha_image_width),
    mt_rand(0,$captcha_image_height),
    mt_rand(0,$captcha_image_width),
    mt_rand(0,$captcha_image_height),
    $image_noise_color
    );
}

/* Create a text box and add 6 captcha letters code in it */
$text_box = imagettfbbox(
    $captcha_font_size,
    0,
    $captcha_font,
    $captcha_code
    ); 
$x = ($captcha_image_width - $text_box[4])/2;
$y = ($captcha_image_height - $text_box[5])/2;
imagettftext(
    $captcha_image,
    $captcha_font_size,
    0,
    $x,
    $y,
    $captcha_text_color,
    $captcha_font,
    $captcha_code
    );

/* Show captcha image in the html page */
// defining the image type to be shown in browser widow
header('Content-Type: image/jpeg'); 
imagejpeg($captcha_image); //showing the image
imagedestroy($captcha_image); //destroying the image instance
$_SESSION['captcha'] = $captcha_code;

function hextorgb ($hexstring){
  $integar = hexdec($hexstring);
  return array("red" => 0xFF & ($integar >> 0x10),
               "green" => 0xFF & ($integar >> 0x8),
               "blue" => 0xFF & $integar);
               }
?>

Result of above code:
Generated captcha image

As you can see in the image, the generated image for captcha has only one color, which is very annoying.

I want each part of the generated captcha image to have different colors so that it looks beautiful in addition to making it harder for robots to guess it.

What I’m looking for is to generate the captcha image as follows:
My desired captcha image

Is there a need for a separate library to generate such a captcha image or can it be implemented with a few changes in the code?