Phar

目录

简介

The Phar class provides a high-level interface to accessing and creating phar archives.

类摘要

Phar

class Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess {

/* 继承的常量 */

const integer FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;

const integer FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;

const integer FilesystemIterator::CURRENT_AS_SELF = 16 ;

const integer FilesystemIterator::CURRENT_MODE_MASK = 240 ;

const integer FilesystemIterator::KEY_AS_PATHNAME = 0 ;

const integer FilesystemIterator::KEY_AS_FILENAME = 256 ;

const integer FilesystemIterator::FOLLOW_SYMLINKS = 512 ;

const integer FilesystemIterator::KEY_MODE_MASK = 3840 ;

const integer FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;

const integer FilesystemIterator::SKIP_DOTS = 4096 ;

const integer FilesystemIterator::UNIX_PATHS = 8192 ;

/* 方法 */

public void addEmptyDir ( string $dirname )

public void addFile ( string $file [, string $localname ] )

public void addFromString ( string $localname , string $contents )

final public static string apiVersion ( void )

public array buildFromDirectory ( string $base_dir [, string $regex ] )

public array buildFromIterator ( Iterator $iter [, string $base_directory ] )

final public static bool canCompress ([ int $type = 0 ] )

final public static bool canWrite ( void )

public Phar compress ( int $compression [, string $extension ] )

public bool compressAllFilesBZIP2 ( void )

public bool compressAllFilesGZ ( void )

public void compressFiles ( int $compression )

public __construct ( string $fname [, int $flags [, string $alias ]] )

public PharData convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

public Phar convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

public bool copy ( string $oldfile , string $newfile )

public int count ( void )

final public static string createDefaultStub ([ string $indexfile [, string $webindexfile ]] )

public Phar decompress ([ string $extension ] )

public bool decompressFiles ( void )

public bool delMetadata ( void )

public bool delete ( string $entry )

public bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] )

public string getAlias ( void )

public mixed getMetadata ( void )

public bool getModified ( void )

public string getPath ( void )

public array getSignature ( void )

public string getStub ( void )

final public static array getSupportedCompression ( void )

final public static array getSupportedSignatures ( void )

public string getVersion ( void )

public bool hasMetadata ( void )

final public static void interceptFileFuncs ( void )

public bool isBuffering ( void )

public mixed isCompressed ( void )

public bool isFileFormat ( int $format )

final public static bool isValidPharFilename ( string $filename [, bool $executable = TRUE ] )

public bool isWritable ( void )

final public static bool loadPhar ( string $filename [, string $alias ] )

final public static bool mapPhar ([ string $alias [, int $dataoffset = 0 ]] )

final public static void mount ( string $pharpath , string $externalpath )

final public static void mungServer ( array $munglist )

public bool offsetExists ( string $offset )

public int offsetGet ( string $offset )

public void offsetSet ( string $offset , string $value )

public bool offsetUnset ( string $offset )

final public static string running ([ bool $retphar = TRUE ] )

public bool setAlias ( string $alias )

public bool setDefaultStub ([ string $index [, string $webindex ]] )

public void setMetadata ( mixed $metadata )

public void setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )

public bool setStub ( string $stub [, int $len = -1 ] )

public void startBuffering ( void )

public void stopBuffering ( void )

public bool uncompressAllFiles ( void )

final public static bool unlinkArchive ( string $archive )

final public static void webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )

}

Phar::addEmptyDir

添加一个空目录到 phar 档案

说明

public void Phar::addEmptyDir ( string $dirname )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

通过这个方法,可以创建一个以 dirname 为路径名的空目录。 这个方法和 ZipArchive::addEmptyDir 类似。

参数

dirname
需要在 phar 档案中创建的空目录名称

返回值

没有返回值, 失败时抛出异常(exception)。

范例

示例 #1 一个 Phar::addEmptyDir 示例

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addEmptyDir('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
    // handle errors here
}
?>

参见

  • PharData::addEmptyDir
  • Phar::addFile
  • Phar::addFromString

Phar::addFile

将一个文件从文件系统添加到 phar 档案中

说明

public void Phar::addFile ( string $file [, string $localname ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

通过这个方法,任何文件或者 URL 可以被添加到 phar 档案中。如果第二个可选参数 localname 被设定, 那么文件则会以该参数为名称保存到档案中,此外,file 参数会被作为路径保存在档案中。 URLs 必须提交 localname 参数,否则会抛出异常。 这个方法与 ZipArchive::addFile 类似。

参数

file
需要添加到 phar 档案的文件在磁盘上的完全(绝对)或者相对路径。

localname
文件保存到档案时的路径。

返回值

没有返回值,失败时会抛出异常。

范例

示例 #1 一个 Phar::addFile 示例

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addFile('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->getContent();

    $a->addFile('/full/path/to/file', 'my/file.txt');
    $c = $a['my/file.txt']->getContent();

    // demonstrate URL usage
    $a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
    // handle errors here
}
?>

参见

  • Phar::offsetSet
  • PharData::addFile
  • Phar::addFromString
  • Phar::addEmptyDir

Phar::addFromString

以字符串的形式添加一个文件到 phar 档案

说明

public void Phar::addFromString ( string $localname , string $contents )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

通过这个方法,任何字符串都可以被添加到 phar 档案中。 文件将会以 localname 为路径保存到档案中。 这个方法与 ZipArchive::addFromString 类似。

参数

localname
文件保存到档案时的路径。

contents
要保存的文件内容。

返回值

没有返回值,失败时会抛出异常。

范例

示例 #1 一个 Phar::addFromString 示例

<?php
try {
    $a = new Phar('/path/to/phar.phar');

    $a->addFromString('path/to/file.txt', 'my simple file');
    $b = $a['path/to/file.txt']->getContent();

    // to add contents from a stream handle for large files, use offsetSet()
    $c = fopen('/path/to/hugefile.bin');
    $a['largefile.bin'] = $c;
    fclose($c);
} catch (Exception $e) {
    // handle errors here
}
?>

参见

  • Phar::offsetSet
  • PharData::addFromString
  • Phar::addFile
  • Phar::addEmptyDir

Phar::apiVersion

Returns the api version

说明

final public static string Phar::apiVersion ( void )

Return the API version of the phar file format that will be used when creating phars. The Phar extension supports reading API version 1.0.0 or newer. API version 1.1.0 is required for SHA-256 and SHA-512 hash, and API version 1.1.1 is required to store empty directories.

参数

返回值

The API version string as in "1.0.0".

范例

示例 #1 A Phar::apiVersion example

<?php
echo Phar::apiVersion();
?>

以上例程会输出:

1.1.1

Phar::buildFromDirectory

Construct a phar archive from the files within a directory

说明

public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Populate a phar archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use Phar::buildFromIterator.

参数

base_dir
The full or relative path to the directory that contains all files to add to the archive.

regex
An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

返回值

Phar::buildFromDirectory returns an associative array mapping internal path of file to the full path of the file on the filesystem.

错误/异常

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

范例

示例 #1 A Phar::buildFromDirectory example

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

参见

  • Phar::buildFromIterator

Phar::buildFromIterator

Construct a phar archive from an iterator

说明

public array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Populate a phar archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the phar to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

参数

iter
Any iterator that either associatively maps phar file to location or returns SplFileInfo objects

base_directory
For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive

返回值

Phar::buildFromIterator returns an associative array mapping internal path of file to the full path of the file on the filesystem.

范例

示例 #1 A Phar::buildFromIterator with SplFileInfo

For most phar archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a phar archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.phar" phar archive:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('/path/to/project')),
    '/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

The file project.phar can then be used immediately. Phar::buildFromIterator does not set values such as compression, metadata, and this can be done after creating the phar archive.

As an interesting note, Phar::buildFromIterator can also be used to copy the contents of an existing phar archive, as the Phar object descends from DirectoryIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new Phar('/path/to/anotherphar.phar')),
    'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

示例 #2 A Phar::buildFromIterator with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
    new ArrayIterator(
     array(
        'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
     )));
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

错误/异常

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

参见

  • Phar::buildFromDirectory

Phar::canCompress

Returns whether phar extension supports compression using either zlib or bzip2

说明

final public static bool Phar::canCompress ([ int $type = 0 ] )

This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.

参数

type
Either Phar::GZ or Phar::BZ2 can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).

返回值

TRUE if compression/decompression is available, FALSE if not.

范例

示例 #1 A Phar::canCompress example

<?php
if (Phar::canCompress()) {
    echo file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
    echo 'no compression available';
}
?>

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • Phar::isCompressed
  • Phar::compressFiles
  • Phar::decompressFiles
  • Phar::getSupportedCompression
  • Phar::convertToExecutable
  • Phar::convertToData

Phar::canWrite

Returns whether phar extension supports writing and creating phars

说明

final public static bool Phar::canWrite ( void )

This static method determines whether write access has been disabled in the system php.ini via the phar.readonly ini variable.

参数

返回值

TRUE if write access is enabled, FALSE if it is disabled.

范例

示例 #1 A Phar::canWrite example

<?php
if (Phar::canWrite()) {
    file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?>

参见

Phar::compress

Compresses the entire Phar archive using Gzip or Bzip2 compression

说明

public Phar Phar::compress ( int $compression [, string $extension ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

For tar-based and phar-based phar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

参数

compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension
By default, the extension is .phar.gz or .phar.bz2 for compressing phar archives, and .phar.tar.gz or .phar.tar.bz2 for compressing tar archives. For decompressing, the default file extensions are .phar and .phar.tar.

返回值

Returns a Phar object.

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

范例

示例 #1 A Phar::compress example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • PharData::compress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::decompress
  • Phar::getSupportedCompression
  • Phar::compressFiles
  • Phar::decompressFiles

Phar::compressAllFilesBZIP2

Compresses all files in the current Phar archive using Bzip2 compression

说明

public bool Phar::compressAllFilesBZIP2 ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">Phar::compressclass="function">Phar::decompressclass="function">Phar::compressFilesclass="function">Phar::decompressFiles替代。

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This method compresses all files in the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files prior to re-compressing with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not available, or if any files are compressed using gzip compression and the zlib extension is not enabled.

范例

示例 #1 A Phar::compressAllFilesBZIP2 example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesBZIP2();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

以上例程会输出:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(true)
bool(false)
string(11) "myfile2.txt"
bool(true)
bool(true)
bool(false)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressedBZIP2
  • PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setUncompressed
  • PharFileInfo::setCompressedGZ
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesGZ
  • Phar::getSupportedCompression
  • Phar::uncompressAllFiles

Phar::compressAllFilesGZ

Compresses all files in the current Phar archive using Gzip compression

说明

public bool Phar::compressAllFilesGZ ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">Phar::compressclass="function">Phar::decompressclass="function">Phar::compressFilesclass="function">Phar::decompressFiles替代。

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

For tar-based phar archives, this method compresses the entire archive using gzip compression. The resulting file can be processed with the gunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the files prior to re-compressing with gzip compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

范例

示例 #1 A Phar::compressAllFilesGZ example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesGZ();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

以上例程会输出:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressedBZIP2
  • PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setUncompressed
  • PharFileInfo::setCompressedGZ
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesBZIP2
  • Phar::getSupportedCompression
  • Phar::uncompressAllFiles

Phar::compressFiles

Compresses all files in the current Phar archive

说明

public void Phar::compressFiles ( int $compression )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

参数

compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

返回值

没有返回值。

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

范例

示例 #1 A Phar::compressFiles example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

以上例程会输出:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::decompressFiles
  • Phar::getSupportedCompression
  • Phar::compress
  • Phar::decompress

Phar::__construct

Construct a Phar archive object

说明

public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

参数

fname
Path to an existing Phar archive or to-be-created archive. The file name's extension must contain .phar.

flags
Flags to pass to parent class RecursiveDirectoryIterator.

alias
Alias with which this Phar archive should be referred to in calls to stream functionality.

错误/异常

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

范例

示例 #1 A Phar::__construct example

<?php
try {
    $p = new Phar('/path/to/my.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME,
                  'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?>

Phar::convertToData

Convert a phar archive to a non-executable tar or zip file

说明

public PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

This method is used to convert an executable phar archive to either a tar or zip file. To make the tar or zip non-executable, the phar stub and phar alias files are removed from the newly created archive.

If no changes are specified, this method throws a BadMethodCallException if the archive is in phar file format. For archives in tar or zip file format, this method converts the archive to a non-executable archive.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format
This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression
This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension
This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

返回值

The method returns a PharData object on success and throws an exception on failure.

错误/异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering and has not concluded with Phar::stopBuffering, and a PharException if any problems are encountered during the phar creation process.

范例

示例 #1 A Phar::convertToData example

Using Phar::convertToData():

<?php
try {
    $tarphar = new Phar('myphar.phar.tar');
    // note that myphar.phar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.tar
    $tar = $tarphar->convertToData();
    // convert to non-executable zip format, creates myphar.zip
    $zip = $tarphar->convertToData(Phar::ZIP);
    // create myphar.tbz
    $tgz = $tarphar->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

参见

  • Phar::convertToExecutable
  • PharData::convertToExecutable
  • PharData::convertToData

Phar::convertToExecutable

Convert a phar archive to another executable phar archive file format

说明

public Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This method is used to convert a phar archive to another file format. For instance, it can be used to create a tar-based executable phar archive from a zip-based executable phar archive, or from an executable phar archive in the phar file format. In addition, it can be used to apply whole-archive compression to a tar or phar-based archive.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format
This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression
This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension
This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

返回值

The method returns a Phar object on success and throws an exception on failure.

错误/异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering and has not concluded with Phar::stopBuffering, an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

范例

示例 #1 A Phar::convertToExecutable example

Using Phar::convertToExecutable():

<?php
try {
    $tarphar = new Phar('myphar.phar.tar');
    // convert it to the phar file format
    // note that myphar.phar.tar is *not* unlinked
    $phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
    // creates myphar.phar.tgz
    $compressed = $phar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

参见

  • Phar::convertToData
  • PharData::convertToExecutable
  • PharData::convertToData

Phar::copy

Copy a file internal to the phar archive to another new file within the phar

说明

public bool Phar::copy ( string $oldfile , string $newfile )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Copy a file internal to the phar archive to another new file within the phar. This is an object-oriented alternative to using copy with the phar stream wrapper.

参数

oldfile

newfile

返回值

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

错误/异常

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

范例

示例 #1 A Phar::copy example

This example shows using Phar::copy and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All Phar methods throw exceptions, whereas the stream wrapper uses trigger_error.

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar['a'] = 'hi';
    $phar->copy('a', 'b');
    echo $phar['b']; // outputs "hi"
} catch (Exception $e) {
    // handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a', 'phar//myphar.phar/c');
echo file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>

Phar::count

Returns the number of entries (files) in the Phar archive

说明

public int Phar::count ( void )

参数

返回值

The number of files contained within this phar, or 0 (the number zero) if none.

范例

示例 #1 A Phar::count example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p['file.txt'] = 'hi';
echo 'The new phar has ' . $p->count() . " entries\n";
?>

以上例程会输出:

The new phar has 0 entries
The new phar has 1 entries

Phar::createDefaultStub

Create a phar-file format specific stub

说明

final public static string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )

This method is intended for creation of phar-file format-specific stubs, and is not intended for use with tar- or zip-based phar archives.

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>

or by simple execution:

php myphar.phar

This method provides a simple and easy method to create a stub that will run a startup file from the phar archive. In addition, different files can be specified for running the phar archive from the command line versus through a web server. The loader stub also calls Phar::interceptFileFuncs to allow easy bundling of a PHP application that accesses the file system. If the phar extension is not present, the loader stub will extract the phar archive to a temporary directory and then operate on the files. A shutdown function erases the temporary files on exit.

返回值

Returns a string containing the contents of a customized bootstrap loader (stub) that allows the created Phar archive to work with or without the Phar extension enabled.

错误/异常

Throws UnexpectedValueException if either parameter is longer than 400 bytes.

范例

示例 #1 A Phar::createDefaultStub example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
    // handle errors
}
?>

参见

  • Phar::setStub
  • Phar::getStub

Phar::decompress

Decompresses the entire Phar archive

说明

public Phar Phar::decompress ([ string $extension ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

For tar-based and phar-based phar archives, this method decompresses the entire archive.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically changes the file extension of the archive, .phar by default for phar archives, or .phar.tar for tar-based phar archives. Alternatively, a file extension may be specified with the second parameter.

参数

extension
For decompressing, the default file extensions are .phar and .phar.tar. Use this parameter to specify another file extension. Be aware that all executable phar archives must contain .phar in their filename.

返回值

A Phar object is returned.

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

范例

示例 #1 A Phar::decompress example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 = $p2->decompress(); // creates /path/to/my.phar
?>

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • PharData::compress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compress
  • Phar::getSupportedCompression
  • Phar::compressFiles
  • Phar::decompressFiles

Phar::decompressFiles

Decompresses all files in the current Phar archive

说明

public bool Phar::decompressFiles ( void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method decompresses all files in the Phar archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

范例

示例 #1 A Phar::decompressFiles example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

以上例程会输出:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressFiles
  • Phar::getSupportedCompression
  • Phar::compress
  • Phar::decompress

Phar::delMetadata

Deletes the global metadata of the phar

说明

public bool Phar::delMetadata ( void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Deletes the global metadata of the phar

参数

返回值

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误/异常

Throws PharException if errors occur while flushing changes to disk.

范例

示例 #1 A Phar::delMetaData example

<?php
try {
    $phar = new Phar('myphar.phar');
    var_dump($phar->getMetadata());
    $phar->setMetadata("hi there");
    var_dump($phar->getMetadata());
    $phar->delMetadata();
    var_dump($phar->getMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

以上例程会输出:

NULL
string(8) "hi there"
NULL

参见

  • Phar::getMetadata
  • Phar::setMetadata
  • Phar::hasMetadata

Phar::delete

删除 phar 档案中的一个文件

说明

public bool Phar::delete ( string $entry )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

删除档案中的一个文件。这个方法与下面示例中调用 unlink 处理数据流包装器的方式等价。

参数

entry
需要删除的文件在档案中的路径。

返回值

成功时返回 TRUE,但是最好还是检查一下是否抛出了异常,如果没有抛出,可以认定操作成功。

错误/异常

如果将修改保存到磁盘时发生了错误,会抛出 PharException 异常。

范例

示例 #1 一个 Phar::delete 示例

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->delete('unlink/me.php');
    // this is equivalent to:
    unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
    // handle errors
}
?>

参见

  • PharData::delete
  • Phar::unlinkArchive

Phar::extractTo

Extract the contents of a phar archive to a directory

说明

public bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] )

Extract all files within a phar archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo.

参数

pathto
Path to extract the given files to

files
The name of a file or directory to extract, or an array of files/directories to extract, NULL to skip this param

overwrite
Set to TRUE to enable overwriting existing files

返回值

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误/异常

Throws PharException if errors occur while flushing changes to disk.

范例

示例 #1 A Phar::extractTo example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->extractTo('/full/path'); // extract all files
    $phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
    $phar->extractTo('/this/path',
        array('file1.txt', 'file2.txt')); // extract 2 files only
    $phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

参见

  • PharData::extractTo

Phar::getAlias

Get the alias for Phar

说明

public string Phar::getAlias ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

Returns the alias or NULL if there's no alias.

Phar::getMetadata

Returns phar archive meta-data

说明

public mixed Phar::getMetadata ( void )

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

参数

No parameters.

返回值

any PHP variable that can be serialized and is stored as meta-data for the Phar archive, or NULL if no meta-data is stored.

范例

示例 #1 A Phar::getMetadata example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello";';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not modify phar:', $e;
}
?>

以上例程会输出:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

参见

  • Phar::setMetadata
  • Phar::delMetadata
  • Phar::hasMetadata

Phar::getModified

Return whether phar was modified

说明

public bool Phar::getModified ( void )

This method can be used to determine whether a phar has either had an internal file deleted, or contents of a file changed in some way.

参数

No parameters.

返回值

TRUE if the phar has been modified since opened, FALSE if not.

Phar::getPath

Get the real path to the Phar archive on disk

说明

public string Phar::getPath ( void )

Warning

本函数还未编写文档,仅有参数列表。

参数

此函数没有参数。

返回值

Phar::getSignature

Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

说明

public array Phar::getSignature ( void )

Returns the verification signature of a phar archive in a hexadecimal string.

参数

返回值

Array with the opened archive's signature in hash key and MD5, SHA-1, SHA-256, SHA-512, or OpenSSL in hash_type. This signature is a hash calculated on the entire phar's contents, and may be used to verify the integrity of the archive. A valid signature is absolutely required of all executable phar archives if the phar.require_hash INI variable is set to true.

Phar::getStub

Return the PHP loader or bootstrap stub of a Phar archive

说明

public string Phar::getStub ( void )

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>

or by simple execution:

php myphar.phar

返回值

Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.

错误/异常

Throws RuntimeException if it is not possible to read the stub from the Phar archive.

范例

示例 #1 A Phar::getStub example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
echo $p->getStub();
echo "==NEXT==\n";
$p->setStub("<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>");
echo $p->getStub();
?>

以上例程会输出:

<?php __HALT_COMPILER(); ?>
==NEXT==
<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>

参见

  • Phar::setStub
  • Phar::createDefaultStub

Phar::getSupportedCompression

Return array of supported compression algorithms

说明

final public static array Phar::getSupportedCompression ( void )

参数

No parameters.

返回值

Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the availability of the zlib extension or the bz2 extension.

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • Phar::compress
  • Phar::decompress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressFiles
  • Phar::decompressFiles

Phar::getSupportedSignatures

Return array of supported signature types

说明

final public static array Phar::getSupportedSignatures ( void )

Return array of supported signature types

参数

No parameters.

返回值

Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or OpenSSL.

参见

  • Phar::getSignature
  • Phar::setSignatureAlgorithm

Phar::getVersion

Return version info of Phar archive

说明

public string Phar::getVersion ( void )

Returns the API version of an opened Phar archive.

参数

返回值

The opened archive's API version. This is not to be confused with the API version that the loaded phar extension will use to create new phars. Each Phar archive has the API version hard-coded into its manifest. See Phar file format documentation for more information.

参见

  • Phar::apiVersion

Phar::hasMetadata

Returns whether phar has global meta-data

说明

public bool Phar::hasMetadata ( void )

Returns whether phar has global meta-data set.

参数

No parameters.

返回值

Returns TRUE if meta-data has been set, and FALSE if not.

范例

示例 #1 A Phar::hasMetadata example

<?php
try {
    $phar = new Phar('myphar.phar');
    var_dump($phar->hasMetadata());
    $phar->setMetadata(array('thing' => 'hi'));
    var_dump($phar->hasMetadata());
    $phar->delMetadata();
    var_dump($phar->hasMetadata());
} catch (Exception $e) {
    // handle error
}
?>

以上例程会输出:

bool(false)
bool(true)
bool(false)

参见

  • Phar::getMetadata
  • Phar::setMetadata
  • Phar::delMetadata

Phar::interceptFileFuncs

Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

说明

final public static void Phar::interceptFileFuncs ( void )

instructs phar to intercept fopen, readfile, file_get_contents, opendir, and all of the stat-related functions. If any of these functions is called from within a phar archive with a relative path, the call is modified to access a file within the phar archive. Absolute paths are assumed to be attempts to load external files from the filesystem.

This function makes it possible to run PHP applications designed to run off of a hard disk as a phar application.

参数

No parameters.

返回值

范例

示例 #1 A Phar::interceptFileFuncs example

<?php
Phar::interceptFileFuncs();
include 'phar://' . __FILE__ . '/file.php';
?>

Assuming that this phar is at /path/to/myphar.phar and it contains file.php and file2.txt, if file.php contains this code:

示例 #2 A Phar::interceptFileFuncs example

<?php
echo file_get_contents('file2.txt');
?>

Normally PHP would search the current directory for file2.txt, which would translate as the directory of file.php, or the current directory of a command-line user. Phar::interceptFileFuncs instructs PHP to consider the current directory to be phar:///path/to/myphar.phar/ and so opens phar:///path/to/myphar.phar/file2.txt in the above example code.

Phar::isBuffering

Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

说明

public bool Phar::isBuffering ( void )

This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to Phar::stopBuffering is needed to enable saving changes.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

返回值

Returns TRUE if the write operations are being buffer, FALSE otherwise.

范例

示例 #1 A Phar::isBuffering example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p2 = new Phar('existingphar.phar');
$p['file1.txt'] = 'hi';
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>
=2=
<?php
$p->startBuffering();
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
$p->stopBuffering();
?>
=3=
<?php
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>

以上例程会输出:

bool(false)
bool(false)
=2=
bool(true)
bool(false)
=3=
bool(false)
bool(false)

参见

  • Phar::startBuffering
  • Phar::stopBuffering

Phar::isCompressed

Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

说明

public mixed Phar::isCompressed ( void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on). Zip-based phar archives cannot be compressed as a file, and so this method will always return FALSE if a zip-based phar archive is queried.

参数

No parameters.

返回值

Phar::GZ, Phar::BZ2 or FALSE

范例

示例 #1 A Phar::isCompressed example

<?php
try {
    $phar1 = new Phar('myphar.zip.phar');
    var_dump($phar1->isCompressed());
    $phar2 = new Phar('myuncompressed.tar.phar');
    var_dump($phar2->isCompressed());
    $phar2->compress(Phar::GZ);
    var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>

以上例程会输出:

bool(false)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::decompress
  • PharFileInfo::compress
  • Phar::decompress
  • Phar::compress
  • Phar::canCompress
  • Phar::compressFiles
  • Phar::decompressFiles
  • Phar::getSupportedCompression

Phar::isFileFormat

Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

说明

public bool Phar::isFileFormat ( int $format )

参数

format
Either Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format of the archive.

返回值

Returns TRUE if the phar archive matches the file format requested by the parameter

错误/异常

PharException is thrown if the parameter is an unknown file format specifier.

参见

  • Phar::convertToExecutable
  • Phar::convertToData

Phar::isValidPharFilename

Returns whether the given filename is a valid phar filename

说明

final public static bool Phar::isValidPharFilename ( string $filename [, bool $executable = TRUE ] )

Returns whether the given filename is a valid phar filename that will be recognized as a phar archive by the phar extension. This can be used to test a name without having to instantiate a phar archive and catch the inevitable Exception that will be thrown if an invalid name is specified.

参数

filename
The name or full path to a phar archive not yet created

executable
This parameter determines whether the filename should be treated as a phar executable archive, or a data non-executable archive

返回值

Returns TRUE if the filename is valid, FALSE if not.

Phar::isWritable

Returns true if the phar archive can be modified

说明

public bool Phar::isWritable ( void )

This method returns TRUE if phar.readonly is 0, and the actual phar archive on disk is not read-only.

参数

No parameters.

返回值

Returns TRUE if the phar archive can be modified

参见

  • Phar::canWrite
  • PharData::isWritable

Phar::loadPhar

Loads any phar archive with an alias

说明

final public static bool Phar::loadPhar ( string $filename [, string $alias ] )

This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts.

参数

filename
the full or relative path to the phar archive to open

alias
The alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a PharException will be thrown if a new alias is specified in this case.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

范例

示例 #1 A Phar::loadPhar example

Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar.

<?php
try {
    Phar::loadPhar('/path/to/phar.phar', 'my.phar');
    echo file_get_contents('phar://my.phar/file.txt');
} catch (PharException $e) {
    echo $e;
}
?>

参见

  • Phar::mapPhar

Phar::mapPhar

Reads the currently executed file (a phar) and registers its manifest

说明

final public static bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )

This static method can only be used inside a Phar archive's loader stub in order to initialize the phar when it is directly executed, or when it is included in another script.

参数

alias
The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

dataoffset
Unused variable, here for compatibility with PEAR's PHP_Archive.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

PharException is thrown if not called directly within PHP execution, if no __HALT_COMPILER(); token is found in the current source file, or if the file cannot be opened for reading.

范例

示例 #1 A Phar::mapPhar example

mapPhar should be used only inside a phar's loader stub. Use loadPhar to load an external phar into memory.

Here is a sample Phar loader stub that uses mapPhar.

<?php
function __autoload($class)
{
    include 'phar://me.phar/' . str_replace('_', '/', $class) . '.php';
}
try {
    Phar::mapPhar('me.phar');
    include 'phar://me.phar/startup.php';
} catch (PharException $e) {
    echo $e->getMessage();
    die('Cannot initialize Phar');
}
__HALT_COMPILER();

参见

  • Phar::loadPhar

Phar::mount

Mount an external path or file to a virtual location within the phar archive

说明

final public static void Phar::mount ( string $pharpath , string $externalpath )

Much like the unix file system concept of mounting external devices to paths within the directory tree, Phar::mount allows referring to external files and directories as if they were inside of an archive. This allows powerful abstraction such as referring to external configuration files as if they were inside the archive.

参数

pharpath
The internal path within the phar archive to use as the mounted path location. This must be a relative path within the phar archive, and must not already exist.

externalpath
A path or URL to an external file or directory to mount within the phar archive

返回值

No return. PharException is thrown on failure.

错误/异常

Throws PharException if any problems occur mounting the path.

范例

示例 #1 A Phar::mount example

The following example shows accessing an external configuration file as if it were a path within a phar archive.

First, the code inside of a phar archive:

<?php
$configuration = simplexml_load_string(file_get_contents(
    Phar::running(false) . '/config.xml'));
?>

Next the external code used to mount the configuration file:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
Phar::mount('phar://config.xml', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

Another method is to put the mounting code inside the stub of the phar archive. Here is an example of setting up a default configuration file if no user configuration is specified:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
if (defined('EXTERNAL_CONFIG')) {
    Phar::mount('config.xml', EXTERNAL_CONFIG);
    if (file_exists(__DIR__ . '/extra_config.xml')) {
        Phar::mount('extra.xml', __DIR__ . '/extra_config.xml');
    }
} else {
    Phar::mount('config.xml', 'phar://' . __FILE__ . '/default_config.xml');
    Phar::mount('extra.xml', 'phar://' . __FILE__ . '/default_extra.xml');
}
// now run the application
include 'phar://' . __FILE__ . '/index.php';
__HALT_COMPILER();
?>

...and the code externally to load this phar archive:

<?php
define('EXTERNAL_CONFIG', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

Phar::mungServer

Defines a list of up to 4 $_SERVER variables that should be modified for execution

说明

final public static void Phar::mungServer ( array $munglist )

Phar::mungServer should only be called within the stub of a phar archive.

Defines a list of up to 4 $_SERVER variables that should be modified for execution. Variables that can be modified to remove traces of phar execution are REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME.

On its own, this method does nothing. Only when combined with Phar::webPhar does it take effect, and only when the requested file is a PHP file to be parsed. Note that the PATH_INFO and PATH_TRANSLATED variables are always modified.

The original values of variables that are modified are stored in the SERVER array with PHAR_ prepended, so for instance SCRIPT_NAME would be saved as PHAR_SCRIPT_NAME.

参数

munglist
an array containing as string indices any of REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an exception, and Phar::mungServer is case-sensitive.

返回值

No return.

错误/异常

Throws UnexpectedValueException if any problems are found with the passed in data.

范例

示例 #1 A Phar::mungServer example

<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>

参见

  • Phar::webPhar
  • Phar::setStub

Phar::offsetExists

Determines whether a file exists in the phar

说明

public bool Phar::offsetExists ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets.

offsetExists() is called whenever isset is called.

参数

offset
The filename (relative path) to look for in a Phar.

返回值

Returns TRUE if the file exists within the phar, or FALSE if not.

范例

示例 #1 A Phar::offsetExists example

<?php
$p = new Phar(dirname(__FILE__) . '/my.phar', 0, 'my.phar');
$p['firstfile.txt'] = 'first file';
$p['secondfile.txt'] = 'second file';
// the next set of lines call offsetExists() indirectly
var_dump(isset($p['firstfile.txt']));
var_dump(isset($p['nothere.txt']));
?>

以上例程会输出:

bool(true)
bool(false)

参见

  • Phar::offsetGet
  • Phar::offsetSet
  • Phar::offsetUnset

Phar::offsetGet

Gets a PharFileInfo object for a specific file

说明

public int Phar::offsetGet ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. Phar::offsetGet is used for retrieving files from a Phar archive.

参数

offset
The filename (relative path) to look for in a Phar.

返回值

A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.

错误/异常

This method throws BadMethodCallException if the file does not exist in the Phar archive.

范例

示例 #1 Phar::offsetGet example

As with all classes that implement the ArrayAccess interface, Phar::offsetGet is automatically called when using the [] angle bracket operator.

<?php
$p = new Phar(dirname(__FILE__) . '/myphar.phar', 0, 'myphar.phar');
$p['exists.txt'] = "file exists\n";
try {
    // automatically calls offsetGet()
    echo $p['exists.txt'];
    echo $p['doesnotexist.txt'];
} catch (BadMethodCallException $e) {
    echo $e;
}
?>

以上例程会输出:

file exists
Entry doesnotexist.txt does not exist

参见

  • Phar::offsetExists
  • Phar::offsetSet
  • Phar::offsetUnset

Phar::offsetSet

Set the contents of an internal file to those of an external file

说明

public void Phar::offsetSet ( string $offset , string $value )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a Phar archive.

参数

offset
The filename (relative path) to modify in a Phar.

value
Content of the file.

返回值

No return values.

错误/异常

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

范例

示例 #1 A Phar::offsetSet example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
    // calls offsetSet
    $p['file.txt'] = 'Hi there';
} catch (Exception $e) {
    echo 'Could not modify file.txt:', $e;
}
?>

参见

  • Phar::offsetExists
  • Phar::offsetGet
  • Phar::offsetUnset

Phar::offsetUnset

Remove a file from a phar

说明

public bool Phar::offsetUnset ( string $offset )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset language construct.

参数

offset
The filename (relative path) to modify in a Phar.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

范例

示例 #1 A Phar::offsetUnset example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
    // deletes file.txt from my.phar by calling offsetUnset
    unset($p['file.txt']);
} catch (Exception $e) {
    echo 'Could not delete file.txt: ', $e;
}
?>

参见

  • Phar::offsetExists
  • Phar::offsetGet
  • Phar::offsetSet
  • Phar::unlinkArchive
  • Phar::delete

Phar::running

Returns the full path on disk or full phar URL to the currently executing Phar archive

说明

final public static string Phar::running ([ bool $retphar = TRUE ] )

Returns the full path to the running phar archive. This is intended for use much like the __FILE__ magic constant, and only has effect inside an executing phar archive.

Inside the stub of an archive, Phar::running returns "". Simply use __FILE__ to access the current running phar inside a stub.

参数

retphar
If FALSE, the full path on disk to the phar archive is returned. If TRUE, a full phar URL is returned.

返回值

Returns the filename if valid, empty string otherwise.

范例

示例 #1 A Phar::running example

For the following example, assume the phar archive is located at /path/to/phar/my.phar.

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

Phar::setAlias

Set the alias for the Phar archive

说明

public bool Phar::setAlias ( string $alias )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Set the alias for the Phar archive, and write it as the permanent alias for this phar archive. An alias can be used internally to a phar archive to ensure that use of the phar stream wrapper to access internal files always works regardless of the location of the phar archive on the filesystem. Another alternative is to rely upon Phar's interception of include or to use Phar::interceptFileFuncs and use relative paths.

参数

alias
A shorthand string that this archive can be referred to in phar stream wrapper access.

返回值

错误/异常

Throws UnexpectedValueException when write access is disabled, and PharException if the alias is already in use or any problems were encountered flushing changes to disk.

范例

示例 #1 A Phar::setAlias example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setAlias('myp.phar');
} catch (Exception $e) {
    // handle error
}
?>

参见

  • Phar::__construct
  • Phar::interceptFileFuncs

Phar::setDefaultStub

Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

说明

public bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This method is a convenience method that combines the functionality of Phar::createDefaultStub and Phar::setStub.

参数

index
Relative path within the phar archive to run if accessed on the command-line

webindex
Relative path within the phar archive to run if accessed through a web browser

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

范例

示例 #1 A Phar::setDefaultStub example

<?php
try {
    $phar = new Phar('myphar.phar');
    $phar->setDefaultStub('cli.php', 'web/index.php');
    // this is the same as:
    // $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
    // handle errors
}
?>

参见

  • Phar::setStub
  • Phar::createDefaultStub

Phar::setMetadata

Sets phar archive meta-data

说明

public void Phar::setMetadata ( mixed $metadata )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Phar::setMetadata should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

参数

metadata
Any PHP variable containing information to store that describes the phar archive

返回值

没有返回值。

范例

示例 #1 A Phar::setMetadata example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello"';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not create and/or modify phar:', $e;
}
?>

以上例程会输出:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

参见

  • Phar::getMetadata
  • Phar::delMetadata
  • Phar::hasMetadata

Phar::setSignatureAlgorithm

Set the signature algorithm for a phar and apply it

说明

public void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL.

Note that all executable phar archives have a signature created automatically, SHA1 by default. data tar- or zip-based archives (archives created with the PharData class) must have their signature created and set explicitly via Phar::setSignatureAlgorithm.

参数

sigtype
One of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL

privatekey
The contents of an OpenSSL private key, as extracted from a certificate or OpenSSL key file:

<?php
$private = openssl_get_privatekey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($private, $pkey);
$p->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
?>

See phar introduction for instructions on naming and placement of the public key file.

返回值

没有返回值。

错误/异常

Throws UnexpectedValueException for many errors, and a PharException if any problems occur flushing changes to disk.

参见

  • Phar::getSupportedSignatures
  • Phar::getSignature

Phar::setStub

Used to set the PHP loader or bootstrap stub of a Phar archive

说明

public bool Phar::setStub ( string $stub [, int $len = -1 ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This method is used to add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.

The loader stub for a Phar archive is used whenever an archive is included directly as in this example:

<?php
include 'myphar.phar';
?>

The loader is not accessed when including a file through the phar stream wrapper like so:

<?php
include 'phar://myphar.phar/somefile.php';
?>

参数

stub
A string or an open stream handle to use as the executable stub for this phar archive.

len

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

范例

示例 #1 A Phar::setStub example

<?php
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['a.php'] = '<?php var_dump("Hello");';
    $p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 'phar://brandnewphar.phar/a.php';
    var_dump($p->getStub());
    $p['b.php'] = '<?php var_dump("World");';
    $p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 'phar://brandnewphar.phar/b.php';
    var_dump($p->getStub());
} catch (Exception $e) {
    echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?>

以上例程会输出:

string(5) "Hello"
string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
string(5) "World"
string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"

更新日志

版本说明
5.4.0Added len parameter.

参见

  • Phar::getStub
  • Phar::createDefaultStub

Phar::startBuffering

Start buffering Phar write operations, do not modify the Phar object on disk

说明

public void Phar::startBuffering ( void )

Although technically unnecessary, the Phar::startBuffering method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. the Phar::startBuffering/Phar::stopBuffering pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

返回值

没有返回值。

范例

示例 #1 A Phar::startBuffering example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub("<?php
function __autoload($class)
{
    include 'phar://myphar.phar/' . str_replace('_', '/', $class) . '.php';
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
?>

参见

  • Phar::stopBuffering
  • Phar::isBuffering

Phar::stopBuffering

Stop buffering write requests to the Phar archive, and save changes to disk

说明

public void Phar::stopBuffering ( void )

Phar::stopBuffering is used in conjunction with the Phar::startBuffering method. Phar::startBuffering can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The Phar::startBuffering/Phar::stopBuffering pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

返回值

没有返回值。

错误/异常

PharException is thrown if any problems are encountered flushing changes to disk.

范例

示例 #1 A Phar::stopBuffering example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file1.txt'] = 'hi';
$p->startBuffering();
var_dump($p->getStub());
$p->setStub("<?php
function __autoload(\$class)
{
    include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php';
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
var_dump($p->getStub());
?>

以上例程会输出:

string(24) "<?php __HALT_COMPILER();"
string(195) "<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();"

参见

  • Phar::startBuffering
  • Phar::isBuffering

Phar::uncompressAllFiles

Uncompresses all files in the current Phar archive

说明

public bool Phar::uncompressAllFiles ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">Phar::compressclass="function">Phar::decompressclass="function">Phar::compressFilesclass="function">Phar::decompressFiles替代。

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This method decompresses all files in the Phar archive. If any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files, and any files compressed using bzip2 compression require the bzip2 extension to decompress the files. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not enabled and any files are compressed using bzip2 compression, or if any files are compressed using gzip compression and the zlib extension is not enabled.

范例

示例 #1 A Phar::uncompressAllFiles example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p->compressAllFilesGZ();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
    $p->uncompressAllFiles();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>

以上例程会输出:

string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressedBZIP2
  • PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setUncompressed
  • PharFileInfo::setCompressedGZ
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesBZIP2
  • Phar::compressAllFilesGZ
  • Phar::getSupportedCompression

Phar::unlinkArchive

Completely remove a phar archive from disk and from memory

说明

final public static bool Phar::unlinkArchive ( string $archive )

Removes a phar archive from disk and memory.

参数

archive
The path on disk to the phar archive.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

PharException is thrown if there are any open file pointers to the phar archive, or any existing Phar, PharData, or PharFileInfo objects referring to the phar archive.

范例

示例 #1 A Phar::unlinkArchive example

<?php
// simple usage
Phar::unlinkArchive('/path/to/my.phar');

// more common example:
$p = new Phar('my.phar');
$fp = fopen('phar://my.phar/file.txt', 'r');
// this creates 'my.phar.gz'
$gp = $p->compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>

参见

  • Phar::delete
  • Phar::offsetUnset

Phar::webPhar

mapPhar for web-based phars. front controller for web applications

说明

final public static void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )

Phar::mapPhar for web-based phars. This method parses $_SERVER['REQUEST_URI'] and routes a request from a web browser to an internal file within the phar archive. In essence, it simulates a web server, routing requests to the correct file, echoing the correct headers and parsing PHP files as needed. This powerful method is part of what makes it easy to convert an existing PHP application into a phar archive. Combined with Phar::mungServer and Phar::interceptFileFuncs, any web application can be used unmodified from a phar archive.

Phar::webPhar should only be called from the stub of a phar archive (see here for more information on what a stub is).

参数

alias
The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

index
The location within the phar of the directory index.

f404
The location of the script to run when a file is not found. This script should output the proper HTTP 404 headers.

mimetypes
An array mapping additional file extensions to MIME type. If the default mapping is sufficient, pass an empty array. By default, these extensions are mapped to these MIME types:

<?php
$mimes = array(
    'phps' => Phar::PHPS, // pass to highlight_file()
    'c' => 'text/plain',
    'cc' => 'text/plain',
    'cpp' => 'text/plain',
    'c++' => 'text/plain',
    'dtd' => 'text/plain',
    'h' => 'text/plain',
    'log' => 'text/plain',
    'rng' => 'text/plain',
    'txt' => 'text/plain',
    'xsd' => 'text/plain',
    'php' => Phar::PHP, // parse as PHP
    'inc' => Phar::PHP, // parse as PHP
    'avi' => 'video/avi',
    'bmp' => 'image/bmp',
    'css' => 'text/css',
    'gif' => 'image/gif',
    'htm' => 'text/html',
    'html' => 'text/html',
    'htmls' => 'text/html',
    'ico' => 'image/x-ico',
    'jpe' => 'image/jpeg',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'js' => 'application/x-javascript',
    'midi' => 'audio/midi',
    'mid' => 'audio/midi',
    'mod' => 'audio/mod',
    'mov' => 'movie/quicktime',
    'mp3' => 'audio/mp3',
    'mpg' => 'video/mpeg',
    'mpeg' => 'video/mpeg',
    'pdf' => 'application/pdf',
    'png' => 'image/png',
    'swf' => 'application/shockwave-flash',
    'tif' => 'image/tiff',
    'tiff' => 'image/tiff',
    'wav' => 'audio/wav',
    'xbm' => 'image/xbm',
    'xml' => 'text/xml',
);
?>

rewrites
The rewrites function is passed a string as its only parameter and must return a string or FALSE.

If you are using fast-cgi or cgi then the parameter passed to the function is the value of the $_SERVER['PATH_INFO'] variable. Otherwise, the parameter passed to the function is the value of the $_SERVER['REQUEST_URI'] variable.

If a string is returned it is used as the internal file path. If FALSE is returned then webPhar() will send a HTTP 403 Denied Code.

返回值

没有返回值。

错误/异常

Throws PharException when unable to open the internal file to output, or if called from a non-stub. If an invalid array value is passed into mimetypes or an invalid callback is passed into rewrites, then UnexpectedValueException is thrown.

范例

示例 #1 A Phar::webPhar example

With the example below, the created phar will display Hello World if one browses to /myphar.phar/index.php or to /myphar.phar, and will display the source of index.phps if one browses to /myphar.phar/index.phps.

<?php
// creating the phar archive:
try {
    $phar = new Phar('myphar.phar');
    $phar['index.php'] = '<?php echo "Hello World"; ?>';
    $phar['index.phps'] = '<?php echo "Hello World"; ?>';
    $phar->setStub('<?php
Phar::webPhar();
__HALT_COMPILER(); ?>');
} catch (Exception $e) {
    // handle error here
}
?>

参见

  • Phar::mungServer
  • Phar::interceptFileFuncs

简介

The PharData class provides a high-level interface to accessing and creating non-executable tar and zip archives. Because these archives do not contain a stub and cannot be executed by the phar extension, it is possible to create and manipulate regular zip and tar files using the PharData class even if phar.readonly php.ini setting is 1.

类摘要

PharData

class PharData extends RecursiveDirectoryIterator {

/* 继承的常量 */

const integer FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;

const integer FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;

const integer FilesystemIterator::CURRENT_AS_SELF = 16 ;

const integer FilesystemIterator::CURRENT_MODE_MASK = 240 ;

const integer FilesystemIterator::KEY_AS_PATHNAME = 0 ;

const integer FilesystemIterator::KEY_AS_FILENAME = 256 ;

const integer FilesystemIterator::FOLLOW_SYMLINKS = 512 ;

const integer FilesystemIterator::KEY_MODE_MASK = 3840 ;

const integer FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;

const integer FilesystemIterator::SKIP_DOTS = 4096 ;

const integer FilesystemIterator::UNIX_PATHS = 8192 ;

/* 方法 */

void addEmptyDir ( string $dirname )

public void Phar::addFile ( string $file [, string $localname ] )

void addFromString ( string $localname , string $contents )

public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

array buildFromIterator ( Iterator $iter [, string $base_directory ] )

PharData compress ( int $compression [, string $extension ] )

void compressFiles ( int $compression )

__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )

PharData convertToData ([ int $format [, int $compression [, string $extension ]]] )

Phar convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )

bool copy ( string $oldfile , string $newfile )

PharData decompress ([ string $extension ] )

bool decompressFiles ( void )

bool delMetadata ( void )

bool delete ( string $entry )

bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] )

bool isWritable ( void )

void offsetSet ( string $offset , string $value )

bool offsetUnset ( string $offset )

bool setAlias ( string $alias )

bool setDefaultStub ([ string $index [, string $webindex ]] )

public void Phar::setMetadata ( mixed $metadata )

public void Phar::setSignatureAlgorithm ( int $sigtype )

bool setStub ( string $stub [, int $len = -1 ] )

/* 继承的方法 */

public void Phar::addEmptyDir ( string $dirname )

public void Phar::addFile ( string $file [, string $localname ] )

public void Phar::addFromString ( string $localname , string $contents )

final public static string Phar::apiVersion ( void )

public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

public array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )

final public static bool Phar::canCompress ([ int $type = 0 ] )

final public static bool Phar::canWrite ( void )

public Phar Phar::compress ( int $compression [, string $extension ] )

public bool Phar::compressAllFilesBZIP2 ( void )

public bool Phar::compressAllFilesGZ ( void )

public void Phar::compressFiles ( int $compression )

public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

public PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

public Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

public bool Phar::copy ( string $oldfile , string $newfile )

public int Phar::count ( void )

final public static string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )

public Phar Phar::decompress ([ string $extension ] )

public bool Phar::decompressFiles ( void )

public bool Phar::delMetadata ( void )

public bool Phar::delete ( string $entry )

public bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] )

public string Phar::getAlias ( void )

public mixed Phar::getMetadata ( void )

public bool Phar::getModified ( void )

public string Phar::getPath ( void )

public array Phar::getSignature ( void )

public string Phar::getStub ( void )

final public static array Phar::getSupportedCompression ( void )

final public static array Phar::getSupportedSignatures ( void )

public string Phar::getVersion ( void )

public bool Phar::hasMetadata ( void )

final public static void Phar::interceptFileFuncs ( void )

public bool Phar::isBuffering ( void )

public mixed Phar::isCompressed ( void )

public bool Phar::isFileFormat ( int $format )

final public static bool Phar::isValidPharFilename ( string $filename [, bool $executable = TRUE ] )

public bool Phar::isWritable ( void )

final public static bool Phar::loadPhar ( string $filename [, string $alias ] )

final public static bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )

final public static void Phar::mount ( string $pharpath , string $externalpath )

final public static void Phar::mungServer ( array $munglist )

public bool Phar::offsetExists ( string $offset )

public int Phar::offsetGet ( string $offset )

public void Phar::offsetSet ( string $offset , string $value )

public bool Phar::offsetUnset ( string $offset )

final public static string Phar::running ([ bool $retphar = TRUE ] )

public bool Phar::setAlias ( string $alias )

public bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )

public void Phar::setMetadata ( mixed $metadata )

public void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )

public bool Phar::setStub ( string $stub [, int $len = -1 ] )

public void Phar::startBuffering ( void )

public void Phar::stopBuffering ( void )

public bool Phar::uncompressAllFiles ( void )

final public static bool Phar::unlinkArchive ( string $archive )

final public static void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] )

}

PharData::addEmptyDir

Add an empty directory to the tar/zip archive

说明

void PharData::addEmptyDir ( string $dirname )

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir.

参数

dirname
The name of the empty directory to create in the phar archive

返回值

no return value, exception is thrown on failure.

范例

示例 #1 A PharData::addEmptyDir example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addEmptyDir('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
    // handle errors here
}
?>

参见

  • Phar::addEmptyDir
  • PharData::addFile
  • PharData::addFromString

PharData::addFile

Add a file from the filesystem to the tar/zip archive

说明

public void Phar::addFile ( string $file [, string $localname ] )

With this method, any file or URL can be added to the tar/zip archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile.

参数

file
Full or relative path to a file on disk to be added to the phar archive.

localname
Path that the file will be stored in the archive.

返回值

no return value, exception is thrown on failure.

范例

示例 #1 A PharData::addFile example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addFile('/full/path/to/file');
    // demonstrates how this file is stored
    $b = $a['full/path/to/file']->getContent();

    $a->addFile('/full/path/to/file', 'my/file.txt');
    $c = $a['my/file.txt']->getContent();

    // demonstrate URL usage
    $a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
    // handle errors here
}
?>

参见

  • PharData::offsetSet
  • Phar::addFile
  • PharData::addFromString
  • PharData::addEmptyDir

PharData::addFromString

Add a file from the filesystem to the tar/zip archive

说明

void PharData::addFromString ( string $localname , string $contents )

With this method, any string can be added to the tar/zip archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString.

参数

localname
Path that the file will be stored in the archive.

contents
The file contents to store

返回值

no return value, exception is thrown on failure.

范例

示例 #1 A PharData::addFromString example

<?php
try {
    $a = new PharData('/path/to/my.tar');

    $a->addFromString('path/to/file.txt', 'my simple file');
    $b = $a['path/to/file.txt']->getContent();

    // to add contents from a stream handle for large files, use offsetSet()
    $c = fopen('/path/to/hugefile.bin');
    $a['largefile.bin'] = $c;
    fclose($c);
} catch (Exception $e) {
    // handle errors here
}
?>

参见

  • PharData::offsetSet
  • Phar::addFromString
  • PharData::addFile
  • PharData::addEmptyDir

PharData::buildFromDirectory

Construct a tar/zip archive from the files within a directory

说明

public array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Populate a tar/zip archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use PharData::buildFromIterator.

参数

base_dir
The full or relative path to the directory that contains all files to add to the archive.

regex
An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

返回值

Phar::buildFromDirectory returns an associative array mapping internal path of file to the full path of the file on the filesystem.

错误/异常

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

范例

示例 #1 A PharData::buildFromDirectory example

<?php
$phar = new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');

$phar2 = new PharData('project2.zip');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
?>

参见

  • Phar::buildFromDirectory
  • PharData::buildFromIterator

PharData::buildFromIterator

Construct a tar or zip archive from an iterator

说明

array PharData::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Populate a tar or zip archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the tar/zip to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

范例

示例 #1 A PharData::buildFromIterator with SplFileInfo

For most tar/zip archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a tar/zip archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.tar" tar archive:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('/path/to/project')),
    '/path/to/project');
?>

The file project.tar can then be used immediately. PharData::buildFromIterator does not set values such as compression, metadata, and this can be done after creating the tar/zip archive.

As an interesting note, PharData::buildFromIterator can also be used to copy the contents of an existing phar, tar or zip archive, as the PharData object descends from DirectoryIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new Phar('/path/to/anotherphar.phar')),
    'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

示例 #2 A PharData::buildFromIterator with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new ArrayIterator(
     array(
        'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
     )));
?>

参数

iter
Any iterator that either associatively maps tar/zip file to location or returns SplFileInfo objects

base_directory
For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the tar/zip archive

返回值

PharData::buildFromIterator returns an associative array mapping internal path of file to the full path of the file on the filesystem.

错误/异常

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

参见

  • Phar::buildFromIterator

PharData::compress

Compresses the entire tar/zip archive using Gzip or Bzip2 compression

说明

PharData PharData::compress ( int $compression [, string $extension ] )

For tar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For zip archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

参数

compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension
By default, the extension is .tar.gz or .tar.bz2 for compressing a tar, and .tar for decompressing.

返回值

A PharData object is returned.

错误/异常

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

范例

示例 #1 A PharData::compress example

<?php
$p = new PharData('/path/to/my.tar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.tar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.tar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.tar already exists
?>

参见

  • Phar::compress

PharData::compressFiles

Compresses all files in the current tar/zip archive

说明

void PharData::compressFiles ( int $compression )

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress to compress an entire tar-based archive.

For Zip-based archives, this method compresses all files in the archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing.

参数

compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

返回值

没有返回值。

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

范例

示例 #1 A PharData::compressFiles example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

以上例程会输出:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • Phar::canCompress
  • Phar::isCompressed
  • PharData::decompressFiles
  • Phar::getSupportedCompression
  • PharData::compress
  • PharData::decompress

PharData::__construct

Construct a non-executable tar or zip archive object

说明

PharData::__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )

参数

fname
Path to an existing tar/zip archive or to-be-created archive

flags
Flags to pass to Phar parent class RecursiveDirectoryIterator.

alias
Alias with which this Phar archive should be referred to in calls to stream functionality.

format
One of the file format constants available within the Phar class.

错误/异常

Throws BadMethodCallException if called twice; UnexpectedValueException if the Phar archive can't be opened.

范例

示例 #1 A PharData::__construct example

<?php
try {
    $p = new PharData('/path/to/my.tar', Phar::CURRENT_AS_FILEINFO | Phar::KEY_AS_FILENAME);
} catch (UnexpectedValueException $e) {
    die('Could not open my.tar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
echo file_get_contents('phar:///path/to/my.tar/example.txt');
?>

PharData::convertToData

Convert a phar archive to a non-executable tar or zip file

说明

PharData PharData::convertToData ([ int $format [, int $compression [, string $extension ]]] )

This method is used to convert a non-executable tar or zip archive to another non-executable format.

If no changes are specified, this method throws a BadMethodCallException. This method should be used to convert a tar archive to zip format or vice-versa. Although it is possible to simply change the compression of a tar archive using this method, it is better to use the PharData::compress method for logical consistency.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format
This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression
This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension
This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

返回值

The method returns a PharData object on success and throws an exception on failure.

错误/异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering and has not concluded with Phar::stopBuffering, and a PharException if any problems are encountered during the phar creation process.

范例

示例 #1 A PharData::convertToData example

Using PharData::convertToData():

<?php
try {
    $tarphar = new PharData('myphar.tar');
    // note that myphar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.zip
    $zip = $tarphar->convertToData(Phar::ZIP);
    // create myphar.tbz
    $tgz = $zip->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

参见

  • Phar::convertToExecutable
  • Phar::convertToData
  • PharData::convertToExecutable

PharData::convertToExecutable

Convert a non-executable tar/zip archive to an executable phar archive

说明

Phar PharData::convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

This method is used to convert a non-executable tar or zip archive to an executable phar archive. Any of the three executable file formats (phar, tar or zip) can be used, and whole-archive compression can also be performed.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format
This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression
This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension
This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

返回值

The method returns a Phar object on success and throws an exception on failure.

错误/异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering and has not concluded with Phar::stopBuffering, an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

范例

示例 #1 A PharData::convertToExecutable example

Using PharData::convertToExecutable():

<?php
try {
    $tarphar = new PharData('myphar.tar');
    // convert it to the phar file format
    // note that myphar.tar is *not* unlinked
    $phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
    // creates myphar.phar.tgz
    $compressed = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

参见

  • Phar::convertToExecutable
  • Phar::convertToData
  • PharData::convertToData

PharData::copy

Copy a file internal to the phar archive to another new file within the phar

说明

bool PharData::copy ( string $oldfile , string $newfile )

Copy a file internal to the tar/zip archive to another new file within the same archive. This is an object-oriented alternative to using copy with the phar stream wrapper.

参数

oldfile

newfile

返回值

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

错误/异常

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

范例

示例 #1 A PharData::copy example

This example shows using PharData::copy and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All PharData methods throw exceptions, whereas the stream wrapper uses trigger_error.

<?php
try {
    $phar = new PharData('myphar.tar');
    $phar['a'] = 'hi';
    $phar->copy('a', 'b');
    echo $phar['b']; // outputs "phar://myphar.tar/b"
} catch (Exception $e) {
    // handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.tar/a', 'phar//myphar.tar/c');
echo file_get_contents('phar://myphar.tar/c'); // outputs "hi"
?>

PharData::decompress

Decompresses the entire Phar archive

说明

PharData PharData::decompress ([ string $extension ] )

For tar-based archives, this method decompresses the entire archive.

For Zip-based archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression.

In addition, this method automatically renames the file extension of the archive, .tar by default. Alternatively, a file extension may be specified with the extension parameter.

参数

extension
For decompressing, the default file extension is .tar. Use this parameter to specify another file extension. Be aware that only executable archives can contain .phar in their filename.

返回值

A PharData object is returned.

错误/异常

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

范例

示例 #1 A PharData::decompress example

<?php
$p = new PharData('/path/to/my.tar.gz');
$p->decompress(); // creates /path/to/my.tar
?>

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • PharData::compress
  • Phar::canCompress
  • Phar::isCompressed
  • PharData::compress
  • Phar::getSupportedCompression
  • PharData::compressFiles
  • PharData::decompressFiles

PharData::decompressFiles

Decompresses all files in the current zip archive

说明

bool PharData::decompressFiles ( void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress to compress an entire tar-based archive.

For Zip-based archives, this method decompresses all files in the archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

范例

示例 #1 A PharData::decompressFiles example

<?php
$p = new PharData('/path/to/my.zip');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressed(Phar::BZ2));
    var_dump($file->isCompressed(Phar::GZ));
}
?>

以上例程会输出:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • PharFileInfo::decompress
  • Phar::canCompress
  • Phar::isCompressed
  • PharData::compressFiles
  • Phar::getSupportedCompression
  • PharData::compress
  • PharData::decompress

PharData::delMetadata

Deletes the global metadata of a zip archive

说明

bool PharData::delMetadata ( void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Deletes the global metadata of the zip archive

参数

返回值

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误/异常

Throws PharException if errors occur while flushing changes to disk.

范例

示例 #1 A PharData::delMetaData example

<?php
try {
    $phar = new PharData('myphar.zip');
    var_dump($phar->getMetadata());
    $phar->setMetadata("hi there");
    var_dump($phar->getMetadata());
    $phar->delMetadata();
    var_dump($phar->getMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

以上例程会输出:

NULL
string(8) "hi there"
NULL

参见

  • Phar::delMetadata

PharData::delete

Delete a file within a tar/zip archive

说明

bool PharData::delete ( string $entry )

Delete a file within an archive. This is the functional equivalent of calling unlink on the stream wrapper equivalent, as shown in the example below.

参数

entry
Path within an archive to the file to delete.

返回值

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误/异常

Throws PharException if errors occur while flushing changes to disk.

范例

示例 #1 A PharData::delete example

<?php
try {
    $phar = new PharData('myphar.zip');
    $phar->delete('unlink/me.php');
    // this is equivalent to:
    unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
    // handle errors
}
?>

参见

  • Phar::delete

PharData::extractTo

Extract the contents of a tar/zip archive to a directory

说明

bool PharData::extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] )

Extract all files within a tar/zip archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo.

参数

pathto
Path to extract the given files to

files
The name of a file or directory to extract, or an array of files/directories to extract

overwrite
Set to TRUE to enable overwriting existing files

返回值

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误/异常

Throws PharException if errors occur while flushing changes to disk.

范例

示例 #1 A PharData::extractTo example

<?php
try {
    $phar = new PharData('myphar.tar');
    $phar->extractTo('/full/path'); // extract all files
    $phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
    $phar->extractTo('/this/path',
        array('file1.txt', 'file2.txt')); // extract 2 files only
    $phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

参见

  • Phar::extractTo

PharData::isWritable

Returns true if the tar/zip archive can be modified

说明

bool PharData::isWritable ( void )

This method returns TRUE if the tar/zip archive on disk is not read-only. Unlike Phar::isWritable, data-only tar/zip archives can be modified even if phar.readonly is set to 1.

参数

No parameters.

返回值

Returns TRUE if the tar/zip archive can be modified

参见

  • Phar::canWrite
  • Phar::isWritable

PharData::offsetSet

Set the contents of a file within the tar/zip to those of an external file or string

说明

void PharData::offsetSet ( string $offset , string $value )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a tar/zip archive.

参数

offset
The filename (relative path) to modify in a tar or zip archive.

value
Content of the file.

返回值

No return values.

错误/异常

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

范例

示例 #1 A PharData::offsetSet example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p = new PharData('/path/to/my.tar');
try {
    // calls offsetSet
    $p['file.txt'] = 'Hi there';
} catch (Exception $e) {
    echo 'Could not modify file.txt:', $e;
}
?>

参见

  • Phar::offsetSet

PharData::offsetUnset

Remove a file from a tar/zip archive

说明

bool PharData::offsetUnset ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset language construct.

参数

offset
The filename (relative path) to modify in the tar/zip archive.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

范例

示例 #1 A PharData::offsetUnset example

<?php
$p = new PharData('/path/to/my.zip');
try {
    // deletes file.txt from my.zip by calling offsetUnset
    unset($p['file.txt']);
} catch (Exception $e) {
    echo 'Could not delete file.txt: ', $e;
}
?>

参见

  • Phar::offsetUnset

PharData::setAlias

Dummy function (Phar::setAlias is not valid for PharData)

说明

bool PharData::setAlias ( string $alias )

Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception.

参数

alias
A shorthand string that this archive can be referred to in phar stream wrapper access. This parameter is ignored.

返回值

错误/异常

Throws PharException on all method calls

参见

  • Phar::setAlias

PharData::setDefaultStub

Dummy function (Phar::setDefaultStub is not valid for PharData)

说明

bool PharData::setDefaultStub ([ string $index [, string $webindex ]] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

参数

index
Relative path within the phar archive to run if accessed on the command-line

webindex
Relative path within the phar archive to run if accessed through a web browser

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws PharException on all method calls

参见

  • Phar::setDefaultStub

Phar::setMetadata

Sets phar archive meta-data

说明

public void Phar::setMetadata ( mixed $metadata )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Phar::setMetadata should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

参数

metadata
Any PHP variable containing information to store that describes the phar archive

返回值

没有返回值。

范例

示例 #1 A Phar::setMetadata example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.php'] = '<?php echo "hello"';
    $p->setMetadata(array('bootstrap' => 'file.php'));
    var_dump($p->getMetadata());
} catch (Exception $e) {
    echo 'Could not create and/or modify phar:', $e;
}
?>

以上例程会输出:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

参见

  • Phar::getMetadata
  • Phar::delMetadata
  • Phar::hasMetadata

Phar::setSignatureAlgorithm

Set the signature algorithm for a phar and apply it

说明

public void Phar::setSignatureAlgorithm ( int $sigtype )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 class="classname">Phar 对象. 否则, 将抛出class="classname">PharException.

Set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::PGP (pgp not yet supported and falls back to SHA-1).

参数

sigtype
One of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::PGP

返回值

没有返回值。

错误/异常

Throws UnexpectedValueException for many errors, BadMethodCallException if called for a zip- or a tar-based phar archive, and a PharException if any problems occur flushing changes to disk.

参见

  • Phar::getSupportedSignatures
  • Phar::getSignature

PharData::setStub

Dummy function (Phar::setStub is not valid for PharData)

说明

bool PharData::setStub ( string $stub [, int $len = -1 ] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

参数

stub
A string or an open stream handle to use as the executable stub for this phar archive. This parameter is ignored.

len

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws PharException on all method calls

更新日志

版本说明
5.4.0Added len parameter.

参见

  • Phar::setStub

简介

The PharFileInfo class provides a high-level interface to the contents and attributes of a single file within a phar archive.

类摘要

PharFileInfo

class PharFileInfo extends SplFileInfo {

/* 方法 */

public void chmod ( int $permissions )

public bool compress ( int $compression )

public __construct ( string $entry )

public bool decompress ( void )

public bool delMetadata ( void )

public int getCRC32 ( void )

public int getCompressedSize ( void )

public string getContent ( void )

public mixed getMetadata ( void )

public int getPharFlags ( void )

public bool hasMetadata ( void )

public bool isCRCChecked ( void )

public bool isCompressed ([ int $compression_type = 9021976 ] )

public bool isCompressedBZIP2 ( void )

public bool isCompressedGZ ( void )

public bool setCompressedBZIP2 ( void )

public bool setCompressedGZ ( void )

public void setMetadata ( mixed $metadata )

public bool setUncompressed ( void )

}

PharFileInfo::chmod

Sets file-specific permission bits

说明

public void PharFileInfo::chmod ( int $permissions )

PharFileInfo::chmod allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the phar.readonly INI variable. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

参数

permissions
permissions (see chmod)

返回值

没有返回值。

范例

示例 #1 A PharFileInfo::chmod example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar('brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.sh'] = '#!/usr/local/lib/php
    <?php echo "hi"; ?>';
    // set executable bit
    $p['file.sh']->chmod(0555);
    var_dump($p['file.sh']->isExecutable());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?>

以上例程会输出:

bool(true)

PharFileInfo::compress

Compresses the current Phar entry with either zlib or bzip2 compression

说明

public bool PharFileInfo::compress ( int $compression )

This method compresses the file inside the Phar archive using either bzip2 compression or zlib compression. The bzip2 or zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed, the respective extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

范例

示例 #1 A PharFileInfo::compress example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressed(Phar::BZ2));
    $p['myfile.txt']->compress(Phar::BZ2);
    var_dump($file->isCompressed(Phar::BZ2));
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

以上例程会输出:

bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::decompress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressFiles
  • Phar::decompressFiles
  • Phar::compress
  • Phar::decompress
  • Phar::getSupportedCompression

PharFileInfo::__construct

Construct a Phar entry object

说明

public PharFileInfo::__construct ( string $entry )

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet through array access.

参数

entry
The full url to retrieve a file. If you wish to retrieve the information for the file my/file.php from the phar boo.phar, the entry should be phar://boo.phar/my/file.php.

错误/异常

Throws BadMethodCallException if __construct() is called twice. Throws UnexpectedValueException if the phar URL requested is malformed, the requested phar cannot be opened, or the file can't be found within the phar.

范例

示例 #1 A PharFileInfo::__construct example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['testfile.txt'] = "hi\nthere\ndude";
    $file = $p['testfile.txt'];
    foreach ($file as $line => $text) {
        echo "line number $line: $text";
    }
    // this also works
    $file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
    foreach ($file as $line => $text) {
        echo "line number $line: $text";
    }
} catch (Exception $e) {
    echo 'Phar operations failed: ', $e;
}
?>

以上例程会输出:

line number 1: hi
line number 2: there
line number 3: dude
line number 1: hi
line number 2: there
line number 3: dude

PharFileInfo::decompress

Decompresses the current Phar entry within the phar

说明

public bool PharFileInfo::decompress ( void )

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

范例

示例 #1 A PharFileInfo::decompress example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file->compress(Phar::GZ);
    var_dump($file->isCompressed());
    $p['myfile.txt']->decompress();
    var_dump($file->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?>

以上例程会输出:

int(4096)
bool(false)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::compress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressFiles
  • Phar::decompressFiles
  • Phar::compress
  • Phar::decompress
  • Phar::getSupportedCompression

PharFileInfo::delMetadata

Deletes the metadata of the entry

说明

public bool PharFileInfo::delMetadata ( void )

Deletes the metadata of the entry, if any.

参数

No parameters.

返回值

Returns TRUE if successful, FALSE if the entry had no metadata. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

错误/异常

Throws PharException if errors occurred while flushing changes to disk, and BadMethodCallException if write access is disabled.

范例

示例 #1 A PharFileInfo::delMetaData example

<?php
try {
    $a = new Phar('myphar.phar');
    $a['hi'] = 'hi';
    var_dump($a['hi']->delMetadata());
    $a['hi']->setMetadata('there');
    var_dump($a['hi']->delMetadata());
    var_dump($a['hi']->delMetadata());
} catch (Exception $e) {
    // handle errors
}
?>

以上例程会输出:

bool(false)
bool(true)
bool(false)

参见

  • PharFileInfo::setMetadata
  • PharFileInfo::hasMetadata
  • PharFileInfo::getMetadata
  • Phar::setMetadata
  • Phar::hasMetadata
  • Phar::getMetadata

PharFileInfo::getCRC32

Returns CRC32 code or throws an exception if CRC has not been verified

说明

public int PharFileInfo::getCRC32 ( void )

This returns the crc32 checksum of the file within the Phar archive.

返回值

The crc32 checksum of the file within the Phar archive.

错误/异常

Throws BadMethodCallException if the file has not yet had its CRC32 verified. This should be impossible with normal use, as the CRC is verified upon opening the file for reading or writing.

范例

示例 #1 A PharFileInfo::getCRC32 example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file->getCRC32();
} catch (Exception $e) {
    echo 'Write operations on my.phar.phar failed: ', $e;
}
?>

以上例程会输出:

3633523372

PharFileInfo::getCompressedSize

Returns the actual size of the file (with compression) inside the Phar archive

说明

public int PharFileInfo::getCompressedSize ( void )

This returns the size of the file within the Phar archive. Uncompressed files will return the same value for getCompressedSize as they will with filesize

返回值

The size in bytes of the file within the Phar archive on disk.

范例

示例 #1 A PharFileInfo::getCompressedSize example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    echo $file->getCompressedSize();
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>

以上例程会输出:

2

参见

  • PharFileInfo::isCompressed
  • PharFileInfo::decompress
  • PharFileInfo::compress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compress
  • Phar::decompress
  • Phar::getSupportedCompression
  • Phar::decompressFiles
  • Phar::compressFiles

PharFileInfo::getContent

Get the complete file contents of the entry

说明

public string PharFileInfo::getContent ( void )

This function behaves like file_get_contents but for Phar.

参数

此函数没有参数。

返回值

Returns the file contents.

PharFileInfo::getMetadata

Returns file-specific meta-data saved with a file

说明

public mixed PharFileInfo::getMetadata ( void )

Return meta-data that was saved in the Phar archive's manifest for this file.

参数

返回值

any PHP variable that can be serialized and is stored as meta-data for the file, or NULL if no meta-data is stored.

范例

示例 #1 A PharFileInfo::getMetadata example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
    var_dump($p['file.txt']->getMetadata());
} catch (Exception $e) {
    echo 'Could not create/modify brandnewphar.phar: ', $e;
}
?>

以上例程会输出:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

参见

  • PharFileInfo::setMetadata
  • PharFileInfo::hasMetadata
  • PharFileInfo::delMetadata
  • Phar::setMetadata
  • Phar::hasMetadata
  • Phar::getMetadata

PharFileInfo::getPharFlags

Returns the Phar file entry flags

说明

public int PharFileInfo::getPharFlags ( void )

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

返回值

The Phar flags (always 0 in the current implementation)

范例

示例 #1 A PharFileInfo::getPharFlags example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->getPharFlags());
} catch (Exception $e) {
    echo 'Could not create/modify my.phar: ', $e;
}
?>

以上例程会输出:

int(0)

PharFileInfo::hasMetadata

Returns the metadata of the entry

说明

public bool PharFileInfo::hasMetadata ( void )

Returns the metadata of a file within a phar archive.

参数

No parameters.

返回值

Returns FALSE if no metadata is set or is NULL, TRUE if metadata is not NULL

参见

  • PharFileInfo::setMetadata
  • PharFileInfo::getMetadata
  • PharFileInfo::delMetadata
  • Phar::setMetadata
  • Phar::hasMetadata
  • Phar::getMetadata

PharFileInfo::isCRCChecked

Returns whether file entry has had its CRC verified

说明

public bool PharFileInfo::isCRCChecked ( void )

This returns whether a file within a Phar archive has had its CRC verified.

返回值

TRUE if the file has had its CRC verified, FALSE if not.

范例

示例 #1 A PharFileInfo::isCRCChecked example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCRCChecked());
} catch (Exception $e) {
    echo 'Create/modify operations failed on my.phar: ', $e;
}
?>

以上例程会输出:

bool(true)

PharFileInfo::isCompressed

Returns whether the entry is compressed

说明

public bool PharFileInfo::isCompressed ([ int $compression_type = 9021976 ] )

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

参数

compression_type
One of Phar::GZ or Phar::BZ2, defaults to any compression.

返回值

TRUE if the file is compressed within the Phar archive, FALSE if not.

范例

示例 #1 A PharFileInfo::isCompressed example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    var_dump($file->isCompressed());
    var_dump($file2->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

以上例程会输出:

bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::decompress
  • PharFileInfo::compress
  • Phar::decompress
  • Phar::compress
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::getSupportedCompression
  • Phar::decompressFiles
  • Phar::compressFiles

PharFileInfo::isCompressedBZIP2

Returns whether the entry is compressed using bzip2

说明

public bool PharFileInfo::isCompressedBZIP2 ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">PharFileInfo::isCompressedclass="function">PharFileInfo::decompressclass="function">PharFileInfo::compress替代。

This returns whether a file is compressed within a Phar archive with Bzip2 compression.

返回值

TRUE if the file is compressed within the Phar archive using Bzip2, FALSE if not.

范例

示例 #1 A PharFileInfo::isCompressedBZIP2 example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedBZIP2());
    var_dump($file2->isCompressedBZIP2());
    var_dump($file3->isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

以上例程会输出:

bool(false)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setUncompressed
  • PharFileInfo::setCompressedGZ
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesBZIP2
  • Phar::compressAllFilesGZ
  • Phar::getSupportedCompression
  • Phar::uncompressAllFiles

PharFileInfo::isCompressedGZ

Returns whether the entry is compressed using gz

说明

public bool PharFileInfo::isCompressedGZ ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">PharFileInfo::isCompressedclass="function">PharFileInfo::decompressclass="function">PharFileInfo::compress替代。

This returns whether a file is compressed within a Phar archive with Gzip compression.

返回值

TRUE if the file is compressed within the Phar archive using Gzip, FALSE if not.

范例

示例 #1 A PharFileInfo::isCompressedGZ example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedGZ());
    var_dump($file2->isCompressedGZ());
    var_dump($file3->isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

以上例程会输出:

bool(false)
bool(true)
bool(false)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressedBZIP2
  • PharFileInfo::isCompressed
  • PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setUncompressed
  • PharFileInfo::setCompressedGZ
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesBZIP2
  • Phar::compressAllFilesGZ
  • Phar::getSupportedCompression
  • Phar::uncompressAllFiles

PharFileInfo::setCompressedBZIP2

Compresses the current Phar entry within the phar using Bzip2 compression

说明

public bool PharFileInfo::setCompressedBZIP2 ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">PharFileInfo::isCompressedclass="function">PharFileInfo::decompressclass="function">PharFileInfo::compress替代。

This method compresses the file inside the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using gzip compression, the zlib extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2 extension is not available.

范例

示例 #1 A PharFileInfo::setCompressedBZIP2 example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedBZIP2());
    $p['myfile.txt']->setCompressedBZIP2();
    var_dump($file->isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

以上例程会输出:

bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressedBZIP2
  • PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ
  • PharFileInfo::setUncompressed
  • PharFileInfo::setCompressedGZ
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesBZIP2
  • Phar::compressAllFilesGZ
  • Phar::getSupportedCompression
  • Phar::uncompressAllFiles

PharFileInfo::setCompressedGZ

Compresses the current Phar entry within the phar using gz compression

说明

public bool PharFileInfo::setCompressedGZ ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">PharFileInfo::isCompressedclass="function">PharFileInfo::decompressclass="function">PharFileInfo::compress替代。

This method compresses the file inside the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the zlib extension is not available.

范例

示例 #1 A PharFileInfo::setCompressedGZ example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedGZ());
    $p['myfile.txt']->setCompressedGZ();
    var_dump($file->isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

以上例程会输出:

bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressedBZIP2
  • PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setUncompressed
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesBZIP2
  • Phar::compressAllFilesGZ
  • Phar::getSupportedCompression
  • Phar::uncompressAllFiles

PharFileInfo::setMetadata

Sets file-specific meta-data saved with a file

说明

public void PharFileInfo::setMetadata ( mixed $metadata )

PharFileInfo::setMetadata should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the PharFileInfo::chmod method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored.

参数

metadata
Any PHP variable containing information to store alongside a file

返回值

没有返回值。

范例

示例 #1 A PharFileInfo::setMetadata example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
    $p['file.txt'] = 'hello';
    $p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
    var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
    echo 'Could not create/modify phar: ', $e;
}
?>

以上例程会输出:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

参见

  • PharFileInfo::hasMetadata
  • PharFileInfo::getMetadata
  • PharFileInfo::delMetadata
  • Phar::setMetadata
  • Phar::hasMetadata
  • Phar::getMetadata

PharFileInfo::setUncompressed

Uncompresses the current Phar entry within the phar, if it is compressed

说明

public bool PharFileInfo::setUncompressed ( void )

Note:

此方法已经从 phar 扩展 2.0.0以上版本中删除。可使用 class="function">PharFileInfo::isCompressedclass="function">PharFileInfo::decompressclass="function">PharFileInfo::compress替代。

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

范例

示例 #1 A PharFileInfo::setUncompressed example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file->setCompressedGZ();
    var_dump($file->isCompressed());
    $p['myfile.txt']->setUncompressed();
    var_dump($file->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?>

以上例程会输出:

bool(true)
bool(false)

参见

  • PharFileInfo::getCompressedSize
  • PharFileInfo::isCompressedBZIP2
  • PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setCompressedGZ
  • Phar::canCompress
  • Phar::isCompressed
  • Phar::compressAllFilesBZIP2
  • Phar::compressAllFilesGZ
  • Phar::getSupportedCompression
  • Phar::uncompressAllFiles

简介

The PharException class provides a phar-specific exception class for try/catch blocks.

类摘要

PharException

class PharException extends Exception {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}