9

Is there a way to determine, at runtime, if a PHP file is running as part of a phar archive?

i.e., a native implementation might look something like this

function isRunningAsPhar()
{
    $first_include = get_included_files()[0];
    return strpos($first_include, '.phar') !== false;
}

However, this might not work if the user has renamed the phar to have a different file extension, or symlinked the phar to remove the file extension.

Alana Storm
  • 164,128
  • 91
  • 395
  • 599

3 Answers3

6

You could use the function Phar::running(); That gives you a path for the executed phar archive. If the path is set then its an archive.

https://secure.php.net/manual/en/phar.running.php

Example from manual:

<?php
$a = Phar::running(); // $a is "phar:///path/to/my.phar"
$b = Phar::running(false); // $b is "/path/to/my.phar"
?>
Luke
  • 1,369
  • 1
  • 13
  • 37
René Höhle
  • 26,716
  • 22
  • 73
  • 82
5

Here is a nice little function that will return a true or false based on whether a file runs in PHAR Archive or not

function isPhar() {
  return Phar::running() !== '';
}

Link: http://lesichkov.co.uk/article/20170928111351676090/handy-php-functions-when-working-with-phar-archives

How to use example:

if(isPhar()){
    echo 'Script is running from PHAR';
} else {
    echo 'Script is running otside PHAR';
}
Sand Fox
  • 3
  • 3
Milan
  • 558
  • 6
  • 13
1

You can evaluate it directly like this:

if (Phar::running()){
    echo "Script is running from a phar";
}

No need to create new unneeded functions.

Wadih M.
  • 12,810
  • 7
  • 47
  • 57