Retrieving the data size in bytes of a PHP ini configuration value

Published on 2024-08-18 • Modified on 2024-08-18

This snippet shows how to retrieve the data size in bytes of a PHP ini configuration value. We can use the ini_parse_quantity function introduced in PHP 8.2. It can accept various arguments; here are the examples extracted form the official PHP documentation:


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet314Trait
{
    public function snippet314(): void
    {
        echo '1024: ', ini_parse_quantity('1024'),PHP_EOL;
        echo '1024M: ', ini_parse_quantity('1024M') ,PHP_EOL;
        echo '512K: ', ini_parse_quantity('512K') ,PHP_EOL;
        echo '0xFFk: ', ini_parse_quantity('0xFFk') ,PHP_EOL;
        echo '0b1010k: ', ini_parse_quantity('0b1010k') ,PHP_EOL;
        echo '0o1024: ', ini_parse_quantity('0o1024') ,PHP_EOL;
        echo '01024: ', ini_parse_quantity('01024') ,PHP_EOL;
        // echo ini_parse_quantity('Foobar'); // Warning: Invalid quantity "Foobar": no valid leading digits, interpreting as "0" for backwards compatibility
        // echo ini_parse_quantity('10F'); // Warning: Invalid quantity "10F": unknown multiplier "F", interpreting as "10" for backwards compatibility

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!


Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil