Software Engineer

reading rpm package info from php

· by jsnby · Read in about 1 min · (152 Words)
Computers

I’m in the process of building a web based rpm/yum repo management utility. I needed to be able to query an rpm file on disk and get the name, version, and release number of the package. I was hoping to find some sort of php interface to librpm, but my search didn’t turn up any existing code. I was hoping to avoid using a call to the exec function, but I ended up getting lazy.

<?php
function getPackageInfoFromFile($file) {
    $info = array();
    $fields = array('name', 'version', 'release');

    if(!file_exists($file))
        return false;

    // Build up the query format string
    $query_format = '%{' . implode('}\t%{', $fields) . '}\n';
    $cmd = sprintf('rpm -q --queryformat \'%s\' -p %s',
                $query_format,
                $file
            );

    exec($cmd, $output, $status);

    if($status != 0 || count($output) == 0)
        return false;

    $tmp = explode("\t", $output[0]);

    for($i=0; $i<count($fields); $i++)
        $info[$fields[$i]] = $tmp[$i];

    return $info;
}

If I have an rpm file at /tmp/maven-2.2.1-0.noarch.rpm, I can do the following:

<?php
$file = '/tmp/maven-2.2.1-0.noarch.rpm';
$info = getPackageInfoFromFile($file);

print_r($info);

Which results in:

Array
(
    [name] => maven
    [version] => 2.2.1
    [release] => 0
)

Of course, modify this to suit your needs. the “fields” array inside the function can be modified to return additional data about the file. A list of the available query tags can be found here.