Determine if PHP files work as part of the `phar` archive

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

ie, the inline implementation might look something like this:

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

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

+5
source share
2 answers

You can use the function Phar::running(); This gives you the path for the executable phar archive. If the path is given, then this is an archive.

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

Example from the manual:

 <?php $a = Phar::running(); // $a is "phar:///path/to/my.phar" $b = Phar::running(false); // $b is "/path/to/my.phar" ?> 
+2
source

Here is a small little function that will return true or false depending on whether the file works in the PHAR archive or not

 function isPhar() { return strlen(Phar::running()) > 0 ? true : false; } 

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

How to use an example:

 if(isPhar()){ echo 'Script is running from PHAR'; } else { echo 'Script is running otside PHAR'; } 
+1
source

Source: https://habr.com/ru/post/1239824/


All Articles