Get Package Version using Composer in PHP

Get Package Version using Composer in PHP

When working on a PHP project that uses Composer, you might occasionally need to retrieve the version of a specific package programmatically. This can be useful for debugging, logging, or displaying version information to users. This tutorial explains how to get package version using Composer in PHP.

Let's say we have the following composer.json file:

{
    "name": "company/my-project",
    "description": "Project description",
    "type": "project",
    "license": "MIT",
    "require": {
        "symfony/console": "^6.4"
    }
}

Composer provides a simple way to get a package version with the Composer\InstalledVersions class. Here's an example of how you can use this class to retrieve the version of a package, such as symfony/console:

<?php

use Composer\InstalledVersions;

require_once __DIR__.'/vendor/autoload.php';

$version = InstalledVersions::getVersion('symfony/console');
echo $version.PHP_EOL; // Example: 6.4.17.0

$version = InstalledVersions::getPrettyVersion('symfony/console');
echo $version.PHP_EOL; // Example: v6.4.17
  • InstalledVersions::getVersion - returns a normalized version of the specified package (e.g., 6.4.17.0).
  • InstalledVersions::getPrettyVersion - returns the original version of the package (e.g., v6.4.17).

Leave a Comment

Cancel reply

Your email address will not be published.