Why hashtable (array implementation) compaction does not kick in in PHP?

I am making a big PHP array and then remove most of the beginning of it. As we know it won’t free the memory only mark removed items as Undef, as explained by Nikita here. However when I put more items to the array it should reach the compaction point and we should see memory reduction, but that is not observed.

Please help to understand why compaction is not happening?

<?php

$items = [];

// hashtable compaction should start at every 2^n size.
$size = pow(2, 18);

for($i=0;$i<$size;$i++) {
    $items[$i] = "string $i";
}
// at this point we reached the maximum tablesize before compaction
// 2^18 is used to make memory consumpotion visible enough.
printf("mem: %d Mb n", memory_get_usage(true) / 1024 / 1024);

// Remove all except the last one
for($i=0;$i<$size-1;$i++) {
    unset($items[$i]); 
}

// here it is expected to see the same memory footprint as nothing is freed,
// only marked as UNDEF.
printf("mem: %d Mb n", memory_get_usage(true) / 1024 / 1024);

// However here we expect to hit the compaction point 
// and see $size-1 elements removed, while 1 added, so memory is expected to go down
$items[] = $i;
printf("mem: %d Mb n", memory_get_usage(true) / 1024 / 1024);

Live example: https://onlinephp.io/c/98970

Setting PHP configuration with apache2handler no longer works

My server was upgrade to Debian 12 which included an newer version of PHP, i.e. 8.2. On this server I have a couple of VirtualHosts. Of which some of them have deviating php values defined. In the VirtualHosts I added these lines:

        php_value post_max_size 10M
        php_value upload_max_filesize 10M

The problem is that these values are now being ignored. This worked for PHP 5.x versions and PHP 7.x versions. However, as mentioned, it gets ignored for PHP 8.2. The PHP 8.2 module is correctly loaded for Apache.

I tried adding

SetEnv PHP_VALUE "upload_max_filesize=10M post_max_size=10M"

to the VirtualHost, however, it does not work either.

php_admin_flag engine Off is set for /home/*/public_html, however my sites are at /var/www/htdocs. This cannot be the issue.

Is there some PHP configuration missing? I am puzzled as to what causes the issue.

React form data not passing correctly to PHP on iPhone when using useState

I’ve developed a webpage using React.js to replace an existing WordPress site. The React build files are deployed on the same server as the WordPress site.

The page includes a booking form where I use the POST method to send form data to a WordPress PHP page for processing. The setup works perfectly on most devices, and the submitted data shows up on the PHP page as expected.

However, when submitting the form from an iPhone, only the count fields (adult and child) are passed successfully. Other fields like name and email do not appear in the $_POST array on the PHP side.

Interestingly:

When I hardcode the values into the fetch request, they pass successfully, even on an iPhone.
This issue only occurs when using useState to manage form data.

Why does the data fail to pass when using useState on an iPhone, and how can I fix this? Any help is appreciated!

  • Counts (adult and child) are passed successfully, even when managed with useState.
  • Other fields (name and email) do not pass when managed with useState.
  • Hardcoding all values (even name and email) works perfectly on all devices, including iPhones.

Apache PHP RestAPI to upload/download [closed]

I know this is probably a duplicate post, but I have a Windows machine with Apache/PHP/MySQL services.
I have to build/develop a rest API function that allows the upload/download of files from the server (not the apache root) with a callback. Where should I start?

GLPI with AlmaLinux and plesk

If I have not misunderstood the official installation instructions, including the specific section on locating directories with information

Adapting to an AlmaLinux server with Plesk to install GLPI on https://subdomain.yourdomain.com

Directory extracted from the installation file:

/var/www/glpi >> /var/www/vhosts/yourdomain.com/subdomain/ 

Directories moved out of the public folder (I have also tried using /public/ as vhost root)

/etc/glpi     >> /var/www/vhosts/yourdomain.com/internal/config
/var/lib/glpi >> /var/www/vhosts/yourdomain.com/internal/files
/var/www/vhosts/yourdomain.com/internal/marketplace

Created file inc/downstream.php

<?php
define('GLPI_CONFIG_DIR', '/var/www/vhosts/yourdomain.com/internal/config');

if (file_exists(GLPI_CONFIG_DIR . '/local_define.php')) {
   require_once GLPI_CONFIG_DIR . '/local_define.php';
}

Created file config/local_define.php

<?php
define('GLPI_VAR_DIR', '/var/www/vhosts/yourdomain.com/internal/files');
define('GLPI_LOG_DIR', '/var/www/vhosts/yourdomain.com/logs/subdomain'); // Plesk original log folder

Additional NGINX directives, without Apache proxy mode (I also tried activating and processing .htaccess with the same problems):

location / {
    # Todas las solicitudes se redirigen a /public/index.php
    rewrite ^ /public/index.php last;
}

location ~ ^/public/index.php$ {
    fastcgi_pass unix:/var/run/plesk/plesk-php82-fpm.sock; # Ajustar según tu entorno
    fastcgi_split_path_info ^(.+.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
#some tests
#location ~ ^/(?!public/).* {
    #   deny all;
    #}

    location /public {
        try_files $uri =404;
    }

    location ~* .(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|otf|eot|map)$ {
        try_files $uri =404;
    }
    // It is not documented, but I don't think it should be accessible    
    location = /status.php {
        allow 127.0.0.1; # Permitir acceso desde localhost
        deny all;
        return 404;
    }

Other additional information that could be interesting:

  • PHP-FPM 8.3.14
  • AlmaLinux 9.5 (Teal Serval)
  • GLPI 10.0.17

open_basedir (PHP):

{WEBSPACEROOT}{/}{:}{TMP}{/}:/var/www/vhosts/yourdomain.com/subdomain/public:/var/www/vhosts/yourdomain.com/subdomain:/var/www/vhosts/yourdomain.com/internal/config:/var/www/vhosts/yourdomain.com/internal/files:/var/www/vhosts/yourdomain.com/internal/install

Still showing the error on the home screen about folder security…

Web server root directory configuration is not safe as it permits
access to non-public files. See installation documentation for more
details.

GLPI folder root

What should be the correct configuration in this scenario?

NOTE 1: Modifying the function that checks security is not an option… glpi/src/system/Requirment/safedocumentroot.php

NOTE 2: The official documentation refers to incbased_config.php files but the operation of the variables should be the same v10.x, (removed on beta v11.X).

enter image description here

Typesense Laravel Scout: Search – Case Insensitivity and Diacritics Handling

Problem

I’m experiencing difficulties with Vietnamese language search using Typesense and Laravel Scout. The current implementation fails to handle two search scenarios:

1. Case Sensitivity

When searching for xịt chống nắng, I only get exact case matches:

  • ✖️ Current: Returns only xịt chống nắng, Xịt chống nắng
  • ✔️ Expected: Should return lowercase and uppercase as well: xịt chống nắng, Xịt chống nắng, XỊT CHỐNG NẮNG

2. Diacritics Handling

When searching using a non-accented version xit chong nang, no results are returned:

  • ✖️ Current: No matches found
  • ✔️ Expected: Should return xịt chống nắng, Xịt chống nắng, XỊT CHỐNG NẮNG

Example

$results = Product::search('xit chong nang')->get();
// or
$results = Product::search('XỊT CHỐNG NẮNG')->get();

How can I configure Typesense to handle Vietnamese text search with:

  • Case-insensitive matching
  • Diacritics-insensitive search

Are there built-in methods or configurations in Typesense for Vietnamese language normalization, or anything else can handle my issue?

Impossible to access to PHPMyAdmin : failed to open c:phppear

Although it did works fine 2 weeks ago, since this morning, after launched Uwamp (in no install mode), if i try to access to PHPMyAdmin, i got this error message :

( ! ) Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

( ! ) Fatal error: Unknown: Failed opening required ‘C:/Users/pierr/OneDrive – alienor.org/Documents/Perso/Sauvegarde/Programmes portables/UwAmp/UwAmp/phpapps/phpmyadmin/index.php’ (include_path=’.;C:phppear’) in Unknown on line 0

I stopped firewall
I tried to define include_path on php_uwamp.ini but there is no “pear” folder on Uwamp
i tried to swap from PHP 5.6.18 to PHP 7.0.3

I downloaded the latest version of uwamp
Nothing helped…

Is this a known issue ? What did i miss ?

Thanks for your help.

searchable select options with ajax

I have a searchable select dropdown, and I want to fetch data from the inventory table, which now contains over 20,000 records. Previously, I used basic PHP and SQL to display data when the inventory had fewer than 2,000 records, and it worked fine. However, as the inventory has grown, I switched to using AJAX to improve performance, but it’s not working as expected. Could you help me identify where the issue might be?

<div class="form-floating form-floating-outline">
<select id="select2Basicc" class="select2 form-select form-select-lg" data-allow-clear="true" name="customer" required>
<option value="">Select Parts...</option>
</select>
<label for="select2Basicc">Select Customer</label> </div>

<code>
    $(document).ready(function () {
        // Initialize Select2 with AJAX
        $('#select2Basicc').select2({
            placeholder: 'Select Parts...',
            ajax: {
                url: 'get_parts.php', // Backend script to fetch data
                type: 'GET',
                dataType: 'json',
                delay: 250, // Delay for better performance
                data: function (params) {
                    return {
                        search: params.term, // Search term
                        page: params.page || 1 // Pagination
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.items, // Items to display
                        pagination: {
                            more: data.pagination.more // Enable "Load More"
                        }
                    };
                },
                cache: true
            },
            minimumInputLength: 2 // Trigger search after 2 characters
        });
    });

and get_parts.php is

$search = $_GET['search']; $page = (int)($_GET['page']); $limit
    = 10; $offset = ($page - 1) * $limit;
    try {
        $stmt = $conn_account_db->prepare("SELECT item_code FROM inventory WHERE item_code LIKE ? LIMIT ? OFFSET ?");
        $likeSearch = "%$search%";
        $stmt->bind_param("sii", $likeSearch, $limit, $offset);
        $stmt->execute();
        $result = $stmt->get_result();
        $items = [];
        while ($row = $result->fetch_assoc()) {
            $items[] = [
                'id' => $row['item_code'], // Value for the option
                'text' => $row['item_code'] // Text to display
            ];
        }
        $stmt = $conn_account_db->prepare("SELECT COUNT(*) as total FROM inventory WHERE item_code LIKE ?");
        $stmt->bind_param("s", $likeSearch);
        $stmt->execute();
        $totalResult = $stmt->get_result()->fetch_assoc();
        $total = $totalResult['total'];
        $more = ($offset + $limit) < $total;
        echo json_encode([
            'items' => $items,
            'pagination' => ['more' => $more]
        ]);} catch (Exception $e) {
        echo json_encode(['items' => [], 'pagination' => ['more' => false]]); } 

Symfony tests not calling my LoginSubscriber, using manual login workaround not returning expected response

I’m using Symfony 6.4, and I have a LoginSubcriber which sets some additional session data depending on the authenticated user’s account setup. This additional session data is essential for the running of the site.

My subscriber is registered in /config/services.yaml as such:

services:
  ...
  AppEventListenerLoginSubscriber:
    tags: [ name: kernel.event_subscriber ]

And it works perfectly when logging in via a browser.

My issue comes when testing. If I call login $client->loginUser($user), then my LoginSubscriber is never called, which makes subsequent requests not work properly because they don’t have the correct session data setup within the LoginSubscriber.

As a way around this, I changed my test to log the user in manually by going through the full flow:

class FullSearchTest extends WebTestCase
{
    public function testPartialSearchRequiresThreeCharacters(): void
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');
        $form = $crawler->selectButton('SIGN IN')->form([
            '_username' => 'admin',
            '_password' => 'password',
        ]);
        $client->submit($form);
        $client->followRedirects();

        $client->request('GET', '/search', [
            'firstName' => 'fo',
        ]);

        $this->assertResponseIsUnprocessable();
    }
}

I run the test with phpunit like php bin/phpunit

The route /search requires the ROLE_USER, so they must be logged in. However, my test fails because the response is 200 OK, and inside the output it’s showing the HTML for the login page, not the content of /search.

If I change $this->assertResponseIsUnprocessable(); to $this->assertResponseRedirects('/'); then it also fails, because it’s not actually redirecting to the login page. If I change my test to remove the login step, and go straight to /search and call $this->assertResponseRedirects('/');, then the test passes. So I’m not convinced that the issue is the user isn’t logged in, it’s more that the response/request data is stuck on the login, rather than changing to the subsequent /search request, despite $client->followRedirects(); being set.

I guess my question is, is there a way to get $client->loginUser($user); to trigger the LoginSubscriber, and if not, is there a way to get my manual login workaround to return the response status/data of subsequent requests, such as /search in this case.

Is using PHP’s SSH2 extension insecure?

Host_A: Ubuntu 18.04.6 LTS, PHP v7.2, OpenSSH v7.6

Host_B: Ubuntu 22.04.5 LTS, OpenSSH v8.9

I’m trying to establish a SSH connection to a remote server (let’s call it “Host_B”) via PHP’s SSH2 extension to execute some commands remotely. “Host_A” would be the server which I am trying to connect from. When I try to connect to Host_B, it always fails with:

ssh2_connect(): Error starting up SSH connection(-5): Unable to exchange encryption keys

ssh2_connect(): Unable to connect to [Host_B]

Also: the following message can be read from the ssh logs from Host_B:

sshd[###]: Unable to negotiate with [Host_A] port 55466: no matching host key type found. Their offer: ssh-rsa,ssh-dss [preauth]

Note: These error messages arise when trying to authenticate with plain password via ssh2_auth_password as well as with ssh2_auth_pubkey_file (Which makes total sense, considering how the error already occurs on ssh2_connect, which happens before either of the two authentication methods). Just wanted to clarify

What I suppose happened here, is that OpenSSH on Host_B refused the connection, because there is no secure algorithm which is supported by both the SSH2 extension by PHP on Host_A and OpenSSH on Host_B.

As of now, it seems that the only two algorithms supported by PHP’s SSH2 extension (even in the latest versions), as stated by PHP documentation, are ssh-rsa and ssh-dss. But both of these algorithms are deprecated and disabled by default in OpenSSH as of version 8.8.

As OpenSSH declared both of these algorithms insecure, I don’t just want to re-enable them in some config and use them as if nothing is wrong with that.

What are my options here? Should this not be a concern?

Edit

The PHP docs also state the following for the hostkeys:

Supported Values are dependent on methods supported by underlying library. See » libssh2 documentation for additional information.

Under the libssh2 docs one can find modern algorithms like ssh-ed25519. But when trying:

ssh2_connect('Host_B', [Port], ['hostkey' => 'ssh-ed25519'])

I get the following PHP error:

ssh2_connect(): Failed overriding HOSTKEY method

Laravel – how to use Uppy for image uploading and saving the Image to a Folder in my server [duplicate]

I have this project with image uploading and I use Uppy for it. The uploaded image are store in an hidden form input as show below;

<input name=”photos[]” type=”hidden” value=”{“id”:”https://tusd.tusdemo.net/files/2b1b4528de1ac8c845f98d5046eb8e5b+Il_EWbeYMoMss0amHhCiziz6ekGHOLOmemYMHngbiDuos6PbTMAZM_YAeYNAfTGZaLA2b6UOpEu1u.svbMlFbjIktx6aykEP_K.kXwt7nnbCF2kK0oCs1Jg4YAWCJaZR“,”storage”:”cache”,”metadata”:{“filename”:”dan1.jpg”,”size”:109472,”mime_type”:”image/jpeg”}}”>

I try to get the image from the url on the hidden form input but I am having issues to get the file.. Here below my Controller code:

$imageUrls = [];

        foreach ($request->photos as $image) {
             
                $url = $image;
                $contents = file_get_contents($url);
                $imageName = time().'-'.uniqid().'.'.$contents->getClientOriginalExtension();
            $resize_full_image->save('assets/uploads/profile_photo' .'/'. $imageName);

When I run the code I get this error;

error “An error occurred while creating product: file_get_contents({“id”:”https://tusd.tusdemo.net/files/5f928ca7ebb25d77d0649a4be5aadfb4+1QMwIHU1bSwQ_rk61mPVZRUBfFpb25iUlxzLDUT6lkVju0V3PflOudWpur0in8Ehknw5bqeuXnnIUFY_vfd8YXCXHwGYmBWPg3D2LTaIkjwIkAQj4KX1DkSeERD.QT9H”,”storage”:”cache”,”metadata”:%7B”filename”:”dan1.jpg”,”size”:109472,”mime_type”:”image/jpeg”%7D}): Failed to open stream: No such file or directory”

Why Does Code Coverage for Custom Modules Fail in Laravel?

I set up PHPUnit to work with two different namespaces in a non-Laravel project, and it works perfectly. This is the folder structure of my working example:

├── docker-compose.yml
├── Dockerfile
├── composer.json
├── phpunit.xml
├── app/
│   └── Example.php
├── modules/
│   └── Example.php
└── tests/
    ├── AppTest.php
    └── ModulesTest.php

In this setup, phpunit.xml looks like this:

<testsuites>
    <testsuite name="Tests">
        <directory>tests</directory>
    </testsuite>
</testsuites>
<source>
    <include>
        <directory>app</directory>
        <directory>modules</directory>
    </include>
</source>

And the namespaces are defined in composer.json as follows:

"autoload": {
    "psr-4": {
        "App\": "app/",
        "Modules\": "modules/"
    }
}

I run the following command to generate the coverage report:

docker compose exec php ./vendor/bin/phpunit --coverage-html coverage-report

In this non-Laravel example, the code coverage report correctly shows both app and modules namespaces covered by tests.

Correct Code Coverage Report for Example App

You can checkout the full repository of my example at https://github.com/iwasherefirst2/poc-coverage

The Issue in Laravel:

When I replicate this setup in a fresh Laravel 10.48.24 project, with the same structure and configuration, the coverage report fails to include the modules folder, even though the tests for it pass successfully.

Failing Code Coverage Report for Laravel App

Here is the Laravel-specific information:

  • Laravel Version: 10.48.24
  • PHP Version: 8.2.26
  • PHPUnit Version: 10.x (same in both projects)

Both projects use the same PHPUnit version, and the tests in Laravel are plain unit tests (use PHPUnitFrameworkTestCase). However, the coverage report for my Laravel app only includes the app namespace, completely omitting modules.

Here is also the full repository to look at https://github.com/iwasherefirst2/poc-laravel-coverage-modules

What I Tried:

  • Ensured the namespace configuration in composer.json is correct and ran composer dump-autoload.
  • Used the same phpunit.xml structure in both projects.
  • Verified that tests for the modules folder run successfully in Laravel.

Key Observations:

  • The Laravel project is identical to the working example, except for the additional Laravel-specific files and dependencies.
  • Despite this, the coverage report excludes the modules namespace in my Laravel app, but not in my simple php app.

Question:
Why does the PHPUnit code coverage report fail to include the modules namespace in Laravel, even though the tests are running and passing? Could this be related to Laravel’s PHPUnit integration or autoload configuration? How can I resolve this and ensure full coverage for both namespaces in Laravel?

generation table of contents for dompdf

i want to create pdf from my html content containing table of content in codeigniter 3 controller method by dompdf;

consider so simple one as described in TOC example ;

i will use that as inline PHP string concatenation in my controller method which is as follow:

    public function generateTableOfContents() {
        $options = new DompdfOptions();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);
        $pdf = new DompdfDompdf($options);

        $htmlContent='
        <html>
        <body>

        <script type="text/php">';
            $font = $pdf->getFontMetrics()->getFont('times', 'normal');

            //$font = Font_Metrics::get_font("helvetica", "bold");
            $GLOBALS['chapters'] = array();
            $GLOBALS['backside'] = $pdf->open_object();
        '</script>

        <h2>Table of Contents</h2>
        <ol>
            <li>Chapter 1 ....................... page %%CH1%%</li>
            <li>Chapter 2 ....................... page %%CH2%%</li>
            <li>Chapter 3 ....................... page %%CH3%%</li>
        </ol>

        <script type="text/php">';
            $pdf->close_object();
        '</script>

        <h2 style="page-break-before: always;">Chapter 1</h2>
        <script type="text/php">';
            $GLOBALS['chapters']['1'] = $pdf->get_page_number();
        '</script>

        <div id="lipsum">
        <p>p1</p>
        <p>p2</p>
        <p>p3</p>

        <h2>Chapter 2</h2>
        <script type="text/php">';
            $GLOBALS['chapters']['2'] = $pdf->get_page_number();
        '</script>

        <p>p4</p>
        <p>p5</p>
        <p>p6</p>
        </div>

        <h2 style="page-break-before: always;">Chapter 3</h2>
        <script type="text/php">';
            $GLOBALS['chapters']['3'] = $pdf->get_page_number();
        '</script>

        <div id="lipsum">
        <p>p7</p>
        <p>p8</p>
        <p>p9</p>
        </div>

        <script type="text/php">';
            foreach ($GLOBALS['chapters'] as $chapter => $page) {
                $pdf->get_cpdf()->objects[$GLOBALS['backside']]['c'] = str_replace( '%%CH'.$chapter.'%%' , $page , $pdf->get_cpdf()->objects[$GLOBALS['backside']]['c'] );
            }
            $pdf->page_script('
                if ($PAGE_NUM==1 ) {
                    $pdf->add_object($GLOBALS["backside"],"add");
                    $pdf->stop_object($GLOBALS["backside"]);
                } 
            ');
        '</script>

        </body>
        </html>';

    $pdf->loadHtml($htmlContent);
    $pdf->setPaper('A4', 'landscape');
    $pdf->render();
    $pdf->stream('document.pdf', ['Attachment' => false]);
   }

but,it can not get access cpdf: Message: Call to undefined method DompdfDompdf::open_object()

how should i mention cpdf to be abled to call inside method.

how should resolve?

thanks in advance.

How to show a custom URL per blog post on a post template [duplicate]

I am building a small blog using a PHP and MySQL CMS (no WordPress etc) and have hit a “skill wall”.

My blog post template is post.php, which uses a GET variable to use a post slug to get content from the database. As such, an example URL could look like this: example.com/post.php?s=my-post-slug.

What I would like to do is use a single template (post.php), but have the URL be: example.com/my-post-slug.

I understand that this is likely an .htaccess task, and have found the following code:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

I tried using this, swapping index.php out for post.php, but no luck.

How can this be done?