Install Composer in Docker

Here is a small snippet adapted from the official instruction:

RUN php -r "copy('', '/tmp/composer.sig');" && \
    php -r "copy('', '/tmp/composer-setup.php');" && \
    php -r '$expected = file_get_contents("/tmp/composer.sig"); $actual = hash_file("sha384", "/tmp/composer-setup.php"); exit(intval(!hash_equals($expected, $actual)));' && \
    php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer && \
    chmod +x /usr/local/bin/composer && \
    rm /tmp/composer-setup.php /tmp/composer.sig

It doesn't require a script file, doesn't deal with environment variables, and doesn't depend on the shell.

PHP code explanation:


// an obvious part, get the signature
$expected = file_get_contents("/tmp/composer.sig");

// this part is from the instruction, calculate the signature
$actual = hash_file("sha384", "/tmp/composer-setup.php");

// the best part
// exit(int) exits with the supplied exit code
    // if the argument is not an int, it will be cast to a string
    // we don't want to trigger exit(string) logic here
        // 0 = EXIT_SUCCESS so negate the result
        !hash_equals($expected, $actual)

strcmp() or <=> or even a simple != can also be used for comparison here but hash_equals() is the safest choice because of the argument type checks and predictable return values.


Comments powered by Disqus