Accessing PHP File inside PHAR Archive through Command Line

249 Views Asked by At

I'm not sure if this is possible, but i am trying to access a PHP File inside the PHAR Archive over the command Line on a RHEL 7.0 machine.

I was able to create the PHAR archive and can use it also over Browser and can use it as a normal site. I have some cronjobs inside the archive which i would like to access. But for some reason when i try to execute the Cronjob on command line i get a error

My code for creation of the PHAR File

<?php
try
{
    $pharFile = '/path/to/phar.phar';

    // clean up
    if (file_exists($pharFile)) 
    {
        unlink($pharFile);
    }

    if (file_exists($pharFile . '.gz')) 
    {
        unlink($pharFile . '.gz');
    }

    // create phar
    $phar = new Phar($pharFile);
    $phar->startBuffering();

    $defaultStub = $phar->createDefaultStub('index.php');

    $phar->buildFromDirectory('/path/to/files/');

    $phar->setStub('<?php
        #!/usr/bin/env php '. PHP_EOL .' 
        Phar::webPhar(NULL,NULL,NULL,array("svg" => "image/svg+xml svg svgz"));
        __HALT_COMPILER(); 
        ?>');

    $phar->stopBuffering();
    $phar->compressFiles(Phar::GZ);
    chmod('/path/to/phar.phar', 0770);
    
    echo "$pharFile successfully created" . PHP_EOL;
}
catch (Exception $e)
{
    echo 'Problem: '.$e->getMessage();
}

Through Web i can access with URL www.example.com/phar.phar/jobs/test.php but on the console via SSH i get a error

php /path/to/phar.phar/jobs/test.php

Could not open input file: /path/to/phar.phar/jobs/test.php

Any ideas what i am doing wrong?

1

There are 1 best solutions below

0
Sascha On

Maybe it is not the best solution but i figured out a way

I added

$phar->setDefaultStub('cmd/index.php', 'index.php');

The index.php in the "cmd" folder only will be called when accessing the phar.phar through command line.

With $_SERVER['argv'][1] i check if a argument is passed called "cron" - if yes if will check the path provided in the second argument $_SERVER['argv'][2]. According to this second value i will include the file

At crontab i call it like this

php /path/to/phar.phar cron module/job_01.php

This should to the job also :)