Phar
- Введение
- Установка и настройка
- Предопределенные константы
- Using Phar Archives
- Creating Phar Archives
- What makes a phar a phar and not a tar or a zip?
- Phar — The Phar class
- Phar::addEmptyDir — Add an empty directory to the phar archive
- Phar::addFile — Add a file from the filesystem to the phar archive
- Phar::addFromString — Add a file from the filesystem to the phar archive
- Phar::apiVersion — Returns the api version
- Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
- Phar::buildFromIterator — Construct a phar archive from an iterator.
- Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
- Phar::canWrite — Returns whether phar extension supports writing and creating phars
- Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
- Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
- Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression
- Phar::compressFiles — Compresses all files in the current Phar archive
- Phar::__construct — Construct a Phar archive object
- Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
- Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
- Phar::copy — Copy a file internal to the phar archive to another new file within the phar
- Phar::count — Returns the number of entries (files) in the Phar archive
- Phar::createDefaultStub — Create a phar-file format specific stub
- Phar::decompress — Decompresses the entire Phar archive
- Phar::decompressFiles — Decompresses all files in the current Phar archive
- Phar::delMetadata — Deletes the global metadata of the phar
- Phar::delete — Delete a file within a phar archive
- Phar::extractTo — Extract the contents of a phar archive to a directory
- Phar::getMetadata — Returns phar archive meta-data
- Phar::getModified — Return whether phar was modified
- Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
- Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
- Phar::getSupportedCompression — Return array of supported compression algorithms
- Phar::getSupportedSignatures — Return array of supported signature types
- Phar::getVersion — Return version info of Phar archive
- Phar::hasMetadata — Returns whether phar has global meta-data
- Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
- Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
- Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
- Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
- Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
- Phar::isWritable — Returns true if the phar archive can be modified
- Phar::loadPhar — Loads any phar archive with an alias
- Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
- Phar::mount — Mount an external path or file to a virtual location within the phar archive
- Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
- Phar::offsetExists — determines whether a file exists in the phar
- Phar::offsetGet — Gets a PharFileInfo object for a specific file
- Phar::offsetSet — set the contents of an internal file to those of an external file
- Phar::offsetUnset — remove a file from a phar
- Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
- Phar::setAlias — Set the alias for the Phar archive
- Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
- Phar::setMetadata — Sets phar archive meta-data
- Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.
- Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
- Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
- Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
- Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive
- Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
- Phar::webPhar — mapPhar for web-based phars. front controller for web applications
- PharData — The PharData class
- PharData::addEmptyDir — Add an empty directory to the tar/zip archive
- PharData::addFile — Add a file from the filesystem to the tar/zip archive
- PharData::addFromString — Add a file from the filesystem to the tar/zip archive
- PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.
- PharData::buildFromIterator — Construct a tar or zip archive from an iterator.
- PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
- PharData::compressFiles — Compresses all files in the current tar/zip archive
- PharData::__construct — Construct a non-executable tar or zip archive object
- PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
- PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
- PharData::copy — Copy a file internal to the phar archive to another new file within the phar
- PharData::decompress — Decompresses the entire Phar archive
- PharData::decompressFiles — Decompresses all files in the current zip archive
- PharData::delMetadata — Deletes the global metadata of a zip archive
- PharData::delete — Delete a file within a tar/zip archive
- PharData::extractTo — Extract the contents of a tar/zip archive to a directory
- PharData::isWritable — Returns true if the tar/zip archive can be modified
- PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string
- PharData::offsetUnset — remove a file from a tar/zip archive
- PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)
- PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)
- Phar::setMetadata — Sets phar archive meta-data
- Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The
- PharData::setStub — dummy function (Phar::setStub is not valid for PharData)
- PharFileInfo — The PharFileInfo class
- PharFileInfo::chmod — Sets file-specific permission bits
- PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
- PharFileInfo::__construct — Construct a Phar entry object
- PharFileInfo::decompress — Decompresses the current Phar entry within the phar
- PharFileInfo::delMetadata — Deletes the metadata of the entry
- PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
- PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
- PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
- PharFileInfo::getPharFlags — Returns the Phar file entry flags
- PharFileInfo::hasMetadata — Returns the metadata of the entry
- PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
- PharFileInfo::isCompressed — Returns whether the entry is compressed
- PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
- PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
- PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression
- PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression
- PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file
- PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed
- PharException — The PharException class
- PharException — The PharException class provides a phar-specific exception class for try/catch blocks.
Коментарии
If you get blank pages when trying to access a phar web-page, then you probably have Suhosin on your PHP (like in Debian and Ubuntu), and you need to ad this to your php.ini to allow execution of PHAR archives :
suhosin.executor.include.whitelist="phar"
Users should set the `sys_temp_dir` directive.
PHAR stores temporary files in either `sys_temp_dir` or the current working directory(CWD).
This is especially important if you're CWD is on a remote file system. Often web server clusters will share a common file system between each web server (using NFS, DFS, etc...). In such scenarios, if you don't set `sys_temp_dir` to a local directory, PHAR will be creating temporary files over the network, which will result in performance and functionality problems.
Here is an apache2 htaccess example that prevents the downloading of phar-Archives by the user:
RewriteEngine on
RewriteRule ^(.*)\.phar$ - [F]
It triggers a "403 - Forbidden" message instead of delivering the archive.
Here is a very simple class to build a phar file from a given source directory. You can use this for your own project and simple deployment.
But my main goal was to show how to use PHAR functions in a simple way.
<?php
class BuildPhar
{
private $_sourceDirectory = null;
private $_stubFile = null;
private $_outputDirectory = null;
private $_pharFileName = null;
/**
* @param $_sourceDirectory // This is the directory where your project is stored.
* @param $stubFile // Name the entry point for your phar file. This file have to be within the source
* directory.
* @param null $_outputDirectory // Directory where the phar file will be placed.
* @param string $pharFileName // Name of your final *.phar file.
*/
public function __construct($_sourceDirectory, $stubFile, $_outputDirectory = null, $pharFileName = 'myPhar.phar') {
if ((file_exists($_sourceDirectory) === false) || (is_dir($_sourceDirectory) === false)) {
throw new Exception('No valid source directory given.');
}
$this->_sourceDirectory = $_sourceDirectory;
if (file_exists($this->_sourceDirectory.'/'.$stubFile) === false) {
throw new Exception('Your given stub file doesn\'t exists.');
}
$this->_stubFile = $stubFile;
if(empty($pharFileName) === true) {
throw new Exception('Your given output name for your phar-file is empty.');
}
$this->_pharFileName = $pharFileName;
if ((empty($_outputDirectory) === true) || (file_exists($_outputDirectory) === false) || (is_dir($_outputDirectory) === false)) {
if ($_outputDirectory !== null) {
trigger_error ( 'Your output directory is invalid. We set the fallback to: "'.dirname(__FILE__).'".', E_USER_WARNING);
}
$this->_outputDirectory = dirname(__FILE__);
} else {
$this->_outputDirectory = $_outputDirectory;
}
$this->prepareBuildDirectory();
$this->buildPhar();
}
private function prepareBuildDirectory() {
if (preg_match('/.phar$/', $this->_pharFileName) == FALSE) {
$this->_pharFileName .= '.phar';
}
if (file_exists($this->_pharFileName) === true) {
unlink($this->_pharFileName);
}
}
private function buildPhar() {
$phar = new Phar($this->_outputDirectory.'/'.$this->_pharFileName);
$phar->buildFromDirectory($this->_sourceDirectory);
$phar->setDefaultStub($this->_stubFile);
}
}
//END Class
//Example Usage:
$builder = new BuildPhar(
dirname(__FILE__).'/_source',
'my_default_stub.php',
dirname(__FILE__).'/_output',
'my-phar-file.phar'
);
Here is a very simple program for creating phar files with CLI. Note that it requires phar.readonly in php.ini set to false (Off).
<?php
$filename = "default";
$dir = "./";
$regex = "/^(?!.*build\\.php)(?:.*)$/";
$main = "main.php";
$shebang = "#!/usr/bin/env php";
$chmod = true;
for ($i = 0; $i < $argc; $i++) {
switch ($argv[$i]) {
case "-o":
$i++;
if ($i >= $argc) {
echo "Missing output file name" . PHP_EOL;
exit(1);
}
$filename = $argv[$i];
break;
case "-i":
$i++;
if ($i >= $argc) {
echo "Missing input directory name" . PHP_EOL;
exit(1);
}
$dir = $argv[$i];
break;
case "-p":
$i++;
if ($i >= $argc) {
echo "Missing regular expression pattern" . PHP_EOL;
exit(1);
}
$regex = $argv[$i];
break;
case "-m":
$i++;
if ($i >= $argc) {
echo "Missing main file" . PHP_EOL;
exit(1);
}
$main = $argv[$i];
break;
case "-b":
$i++;
if ($i >= $argc) {
echo "Missing shebang of file" . PHP_EOL;
exit(1);
}
$shebang = $argv[$i];
break;
case "--no-chmod":
$chmod = false;
break;
}
}
if (file_exists($filename)) unlink($filename);
$phar = new Phar($filename);
$phar->buildFromDirectory($dir, $regex);
$phar->setStub(($shebang ? $shebang . PHP_EOL : "") . $phar->createDefaultStub($main));
if ($chmod) {
chmod($filename, fileperms($phar) | 0700);
}
when read via phar://, stream will unserialize object including phar file
Use this to create phar
<?php
// create new Phar
$phar = new Phar('lemon.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); ? >');
// add object of any class as meta data
class AnyClass {}
$object = new AnyClass;
$object->data = 'Chanh';
$phar->setMetadata($object);
$phar->stopBuffering();
?>
and read it by:
<?php
class AnyClass {
function __destruct() {
echo $this->data;
}
}
// output: Chanh
file_get_contents('phar://test.phar');
?>