Book/phar-Phpdoc专题

Phar

目录

简介

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

类摘要

Phar

class Phar extends RecursiveDirectoryIterator implements <span class="interfacename">Countable <span class="oointerface">, ArrayAccess {

/* 继承的常量 */

const int FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;

const int FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;

const int FilesystemIterator::CURRENT_AS_SELF = 16 ;

const int FilesystemIterator::CURRENT_MODE_MASK = 240 ;

const int FilesystemIterator::KEY_AS_PATHNAME = 0 ;

const int FilesystemIterator::KEY_AS_FILENAME = 256 ;

const int FilesystemIterator::FOLLOW_SYMLINKS = 512 ;

const int FilesystemIterator::KEY_MODE_MASK = 3840 ;

const int FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;

const int FilesystemIterator::SKIP_DOTS = 4096 ;

const int FilesystemIterator::UNIX_PATHS = 8192 ;

/* 方法 */

public void addEmptyDir ( <span class="methodparam">string $dirname )

public void addFile ( <span class="methodparam">string $file [, string $localname ] )

public void addFromString ( <span class="methodparam">string $localname , string $contents )

final public static string apiVersion ( <span class="methodparam">void )

public array buildFromDirectory ( <span class="methodparam">string $base_dir [, string $regex ] )

public array buildFromIterator ( <span class="methodparam">Iterator $iter [, string $base_directory ] )

final public static bool canCompress ([ <span class="methodparam">int $type<span class="initializer"> = 0 ] )

final public static bool canWrite ( <span class="methodparam">void )

public Phar compress ( <span class="methodparam">int $compression [, string $extension ] )

public void compressFiles ( <span class="methodparam">int $compression )

public <span class="methodname">__construct ( <span class="methodparam">string $fname [, int $flags [, string $alias ]] )

public PharData convertToData ([ <span class="methodparam">int $format<span class="initializer"> = 9021976 [, <span class="methodparam">int $compression<span class="initializer"> = 9021976 [, <span class="methodparam">string $extension ]]] )

public Phar convertToExecutable ([ <span class="methodparam">int $format<span class="initializer"> = 9021976 [, <span class="methodparam">int $compression<span class="initializer"> = 9021976 [, <span class="methodparam">string $extension ]]] )

public bool copy ( <span class="type">string $oldfile , <span class="methodparam">string $newfile )

public int <span class="methodname">count ( void )

final public static string createDefaultStub ([ <span class="methodparam">string $indexfile [, string $webindexfile ]] )

public Phar decompress ([ <span class="methodparam">string $extension ] )

public bool decompressFiles ( <span class="methodparam">void )

public bool delMetadata ( <span class="methodparam">void )

public bool delete ( <span class="type">string $entry )

public bool extractTo ( <span class="methodparam">string $pathto [, <span class="type">stringarray<span class="type">null $files = null [, <span class="type">bool $overwrite = false ]] )

public string getAlias ( <span class="methodparam">void )

public mixed getMetadata ( <span class="methodparam">void )

public bool getModified ( <span class="methodparam">void )

public string getPath ( <span class="methodparam">void )

public array getSignature ( <span class="methodparam">void )

public string getStub ( <span class="methodparam">void )

final public static array getSupportedCompression ( <span class="methodparam">void )

final public static array getSupportedSignatures ( <span class="methodparam">void )

public string getVersion ( <span class="methodparam">void )

public bool hasMetadata ( <span class="methodparam">void )

final public static void interceptFileFuncs ( <span class="methodparam">void )

public bool isBuffering ( <span class="methodparam">void )

public mixed isCompressed ( <span class="methodparam">void )

public bool isFileFormat ( <span class="methodparam">int $format )

final public static bool isValidPharFilename ( <span class="methodparam">string $filename [, bool $executable = true ] )

public bool isWritable ( <span class="methodparam">void )

final public static bool loadPhar ( <span class="methodparam">string $filename [, string $alias ] )

final public static bool mapPhar ([ <span class="methodparam">string $alias [, int $dataoffset = 0 ]] )

final public static void mount ( <span class="type">string $pharpath , <span class="methodparam">string $externalpath )

final public static void mungServer ( <span class="methodparam">array $munglist )

public bool offsetExists ( <span class="methodparam">string $offset )

public <span class="type">PharFileInfo <span class="methodname">offsetGet ( <span class="type">string $offset )

public void offsetSet ( <span class="methodparam">string $offset , string $value )

public bool offsetUnset ( <span class="methodparam">string $offset )

final public static string running ([ <span class="methodparam">bool $retphar<span class="initializer"> = true ] )

public bool setAlias ( <span class="methodparam">string $alias )

public bool setDefaultStub ([ <span class="methodparam">string $index [, string $webindex ]] )

public void setMetadata ( <span class="methodparam">mixed $metadata )

public void setSignatureAlgorithm ( <span class="methodparam">int $sigtype [, string $privatekey ] )

public bool setStub ( <span class="methodparam">string $stub [, int $len<span class="initializer"> = -1 ] )

public void startBuffering ( <span class="methodparam">void )

public void stopBuffering ( <span class="methodparam">void )

final public static bool unlinkArchive ( <span class="methodparam">string $archive )

final public static void webPhar ([ <span class="methodparam">string $alias [, string $index<span class="initializer"> = "index.php" [, <span class="methodparam">string $f404 [, array $mimetypes [, <span class="type">callable $rewrites ]]]]] )

}

Phar::addEmptyDir

添加一个空目录到 phar 档案

说明

public void Phar::addEmptyDir ( <span class="methodparam">string $dirname )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 ( <span class="methodparam">string $file [, string $localname ] )

Note:

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

通过这个方法,任何文件或者 URL 可以被添加到 phar 档案中。如果第二个可选参数 localname 被设定, 那么文件则会以该参数为名称保存到档案中,此外,file 参数会被作为路径保存在档案中。 URLs 必须提交 localname 参数,否则会抛出异常。 这个方法与 <span class="function">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 ( <span class="methodparam">string $localname , string $contents )

Note:

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

通过这个方法,任何字符串都可以被添加到 phar 档案中。 文件将会以 localname 为路径保存到档案中。 这个方法与 <span class="function">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 ( <span class="methodparam">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 ( <span class="methodparam">string $base_dir [, string $regex ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 <span class="function">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 <span class="classname">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 ( <span class="methodparam">Iterator $iter [, string $base_directory ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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. <span class="function">Phar::buildFromIterator does not set values such as compression, metadata, and this can be done after creating the phar archive.

As an interesting note, <span class="function">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 <span class="classname">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 <span class="classname">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 ([ <span class="methodparam">int $type<span class="initializer"> = 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 ( <span class="methodparam">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 ( <span class="methodparam">int $compression [, string $extension ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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::compressFiles

Compresses all files in the current Phar archive

说明

public void Phar::compressFiles ( <span class="methodparam">int $compression )

Note:

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

For tar-based phar archives, this method throws a <span class="classname">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 <span class="methodname">Phar::__construct ( <span class="methodparam">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 <span class="classname">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 ([ <span class="methodparam">int $format<span class="initializer"> = 9021976 [, <span class="methodparam">int $compression<span class="initializer"> = 9021976 [, <span class="methodparam">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 <span class="classname">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 <span class="function">Phar::startBuffering and has not concluded with Phar::stopBuffering, and a <span class="classname">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 ([ <span class="methodparam">int $format<span class="initializer"> = 9021976 [, <span class="methodparam">int $compression<span class="initializer"> = 9021976 [, <span class="methodparam">string $extension ]]] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 <span class="classname">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 <span class="function">Phar::startBuffering and has not concluded with Phar::stopBuffering, an <span class="classname">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 ( <span class="methodparam">string $oldfile , string $newfile )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 <span class="function">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 <span class="function">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 <span class="methodname">Phar::count ( <span class="methodparam">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 ([ <span class="methodparam">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 <span class="function">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 ([ <span class="methodparam">string $extension ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 ( <span class="methodparam">void )

Note:

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

For tar-based phar archives, this method throws a <span class="classname">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 ( <span class="methodparam">void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 ( <span class="methodparam">string $entry )

Note:

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

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

参数

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

返回值

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

错误/异常

如果将修改保存到磁盘时发生了错误,会抛出 <span class="classname">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 ( <span class="methodparam">string $pathto [, <span class="type">stringarray<span class="type">null $files = null [, <span class="type">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 <span class="function">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 ( <span class="methodparam">void )

Warning

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

参数

此函数没有参数。

返回值

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

Phar::getMetadata

Returns phar archive meta-data

说明

public mixed Phar::getMetadata ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">void )

Warning

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

参数

此函数没有参数。

返回值

Phar::getSignature

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

说明

public array Phar::getSignature ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">void )

instructs phar to intercept fopen, <span class="function">readfile, <span class="function">file_get_contents, <span class="function">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. <span class="function">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 ( <span class="methodparam">void )

This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to <span class="function">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 ( <span class="methodparam">void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">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 ([ <span class="methodparam">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 ( <span class="methodparam">string $pharpath , string $externalpath )

Much like the unix file system concept of mounting external devices to paths within the directory tree, <span class="function">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 ( <span class="methodparam">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 <span class="function">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 ( <span class="methodparam">string $offset )

This is an implementation of the <span class="interfacename">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 <span class="type">PharFileInfo <span class="methodname">Phar::offsetGet ( <span class="methodparam">string $offset )

This is an implementation of the <span class="interfacename">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 <span class="classname">ArrayAccess interface, <span class="methodname">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 ( <span class="methodparam">string $offset , string $value )

Note:

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

This is an implementation of the <span class="interfacename">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;
}
?>

注释

Note: <span class="function">Phar::addFile, <span class="function">Phar::addFromString and <span class="function">Phar::offsetSet save a new phar archive each time they are called. If performance is a concern, <span class="function">Phar::buildFromDirectory or <span class="function">Phar::buildFromIterator should be used instead.

参见

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

Phar::offsetUnset

Remove a file from a phar

说明

public bool Phar::offsetUnset ( <span class="methodparam">string $offset )

Note:

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

This is an implementation of the <span class="interfacename">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 ([ <span class="methodparam">bool $retphar<span class="initializer"> = 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, <span class="function">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 ( <span class="methodparam">string $alias )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 <span class="function">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 <span class="classname">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 ([ <span class="methodparam">string $index [, string $webindex ]] )

Note:

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

This method is a convenience method that combines the functionality of Phar::createDefaultStub and <span class="function">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 ( <span class="methodparam">mixed $metadata )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 ( <span class="methodparam">int $sigtype [, string $privatekey ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 <span class="function">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 ( <span class="methodparam">string $stub [, int $len<span class="initializer"> = -1 ] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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(); ?>"

参见

  • Phar::getStub
  • Phar::createDefaultStub

Phar::startBuffering

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

说明

public void Phar::startBuffering ( <span class="methodparam">void )

Although technically unnecessary, the <span class="function">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/<span class="function">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 ( <span class="methodparam">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/<span class="function">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::unlinkArchive

Completely remove a phar archive from disk and from memory

说明

final public static bool Phar::unlinkArchive ( <span class="methodparam">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 <span class="classname">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 ([ <span class="methodparam">string $alias [, string $index<span class="initializer"> = "index.php" [, <span class="methodparam">string $f404 [, array $mimetypes [, <span class="type">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 <span class="function">Phar::mungServer and <span class="function">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 <span class="classname">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 implements <span class="interfacename">Countable <span class="oointerface">, ArrayAccess {

/* 继承的常量 */

const int FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;

const int FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;

const int FilesystemIterator::CURRENT_AS_SELF = 16 ;

const int FilesystemIterator::CURRENT_MODE_MASK = 240 ;

const int FilesystemIterator::KEY_AS_PATHNAME = 0 ;

const int FilesystemIterator::KEY_AS_FILENAME = 256 ;

const int FilesystemIterator::FOLLOW_SYMLINKS = 512 ;

const int FilesystemIterator::KEY_MODE_MASK = 3840 ;

const int FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;

const int FilesystemIterator::SKIP_DOTS = 4096 ;

const int FilesystemIterator::UNIX_PATHS = 8192 ;

/* 方法 */

public void addEmptyDir ( <span class="methodparam">string $dirname )

public void addFile ( <span class="methodparam">string $file [, string $localname ] )

public void addFromString ( <span class="methodparam">string $localname , string $contents )

public array buildFromDirectory ( <span class="methodparam">string $base_dir [, string $regex ] )

public array buildFromIterator ( <span class="methodparam">Iterator $iter [, string $base_directory ] )

public PharData compress ( <span class="methodparam">int $compression [, string $extension ] )

public void compressFiles ( <span class="methodparam">int $compression )

public <span class="methodname">__construct ( <span class="methodparam">string $fname [, int $flags [, string $alias [, <span class="type">int $format = Phar::TAR ]]] )

public PharData convertToData ([ <span class="methodparam">int $format [, int $compression [, <span class="type">string $extension ]]] )

public Phar convertToExecutable ([ <span class="methodparam">int $format [, int $compression [, <span class="type">string $extension ]]] )

public bool copy ( <span class="type">string $oldfile , <span class="methodparam">string $newfile )

public PharData decompress ([ <span class="methodparam">string $extension ] )

public bool decompressFiles ( <span class="methodparam">void )

public bool delMetadata ( <span class="methodparam">void )

public bool delete ( <span class="type">string $entry )

public bool extractTo ( <span class="methodparam">string $pathto [, <span class="type">stringarray<span class="type">null $files = null [, <span class="type">bool $overwrite = false ]] )

public bool isWritable ( <span class="methodparam">void )

public void offsetSet ( <span class="methodparam">string $offset , string $value )

public bool offsetUnset ( <span class="methodparam">string $offset )

public bool setAlias ( <span class="methodparam">string $alias )

public bool setDefaultStub ([ <span class="methodparam">string $index [, string $webindex ]] )

public void setMetadata ( <span class="methodparam">mixed $metadata )

public void setSignatureAlgorithm ( <span class="methodparam">int $sigtype )

public bool setStub ( <span class="methodparam">string $stub [, int $len<span class="initializer"> = -1 ] )

}

PharData::addEmptyDir

Add an empty directory to the tar/zip archive

说明

public void PharData::addEmptyDir ( <span class="methodparam">string $dirname )

With this method, an empty directory is created with path dirname. This method is similar to <span class="function">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 PharData::addFile ( <span class="methodparam">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 <span class="function">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
}
?>

注释

Note: <span class="function">PharData::addFile, <span class="function">PharData::addFromString and <span class="function">PharData::offsetSet save a new phar archive each time they are called. If performance is a concern, <span class="function">PharData::buildFromDirectory or <span class="function">PharData::buildFromIterator should be used instead.

参见

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

PharData::addFromString

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

说明

public void PharData::addFromString ( <span class="methodparam">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 <span class="function">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
}
?>

注释

Note: <span class="function">PharData::addFile, <span class="function">PharData::addFromString and <span class="function">PharData::offsetSet save a new phar archive each time they are called. If performance is a concern, <span class="function">PharData::buildFromDirectory or <span class="function">PharData::buildFromIterator should be used instead.

参见

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

PharData::buildFromDirectory

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

说明

public array PharData::buildFromDirectory ( <span class="methodparam">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 <span class="function">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 <span class="classname">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

说明

public array PharData::buildFromIterator ( <span class="methodparam">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. <span class="function">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, <span class="function">PharData::buildFromIterator can also be used to copy the contents of an existing phar, tar or zip archive, as the PharData object descends from <span class="classname">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 <span class="classname">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 <span class="classname">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

说明

public PharData PharData::compress ( <span class="methodparam">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

说明

public void PharData::compressFiles ( <span class="methodparam">int $compression )

For tar-based archives, this method throws a <span class="classname">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

说明

public <span class="methodname">PharData::__construct ( <span class="methodparam">string $fname [, int $flags [, string $alias [, <span class="type">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 <span class="classname">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

说明

public PharData PharData::convertToData ([ <span class="methodparam">int $format [, int $compression [, <span class="type">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 <span class="classname">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 <span class="function">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 <span class="function">Phar::startBuffering and has not concluded with Phar::stopBuffering, and a <span class="classname">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

说明

public Phar PharData::convertToExecutable ([ <span class="methodparam">int $format [, int $compression [, <span class="type">string $extension ]]] )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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 <span class="classname">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 <span class="function">Phar::startBuffering and has not concluded with Phar::stopBuffering, an <span class="classname">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

说明

public bool PharData::copy ( <span class="methodparam">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 <span class="function">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 <span class="function">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

说明

public PharData PharData::decompress ([ <span class="methodparam">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

说明

public bool PharData::decompressFiles ( <span class="methodparam">void )

Note:

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

For tar-based archives, this method throws a <span class="classname">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

说明

public bool PharData::delMetadata ( <span class="methodparam">void )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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

说明

public bool PharData::delete ( <span class="methodparam">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

说明

public bool PharData::extractTo ( <span class="methodparam">string $pathto [, <span class="type">stringarray<span class="type">null $files = null [, <span class="type">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 <span class="function">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

说明

public bool PharData::isWritable ( <span class="methodparam">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

说明

public void PharData::offsetSet ( <span class="methodparam">string $offset , string $value )

This is an implementation of the <span class="interfacename">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;
}
?>

注释

Note: <span class="function">PharData::addFile, <span class="function">PharData::addFromString and <span class="function">PharData::offsetSet save a new phar archive each time they are called. If performance is a concern, <span class="function">PharData::buildFromDirectory or <span class="function">PharData::buildFromIterator should be used instead.

参见

  • Phar::offsetSet

PharData::offsetUnset

Remove a file from a tar/zip archive

说明

public bool PharData::offsetUnset ( <span class="methodparam">string $offset )

This is an implementation of the <span class="interfacename">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)

说明

public bool PharData::setAlias ( <span class="methodparam">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)

说明

public bool PharData::setDefaultStub ([ <span class="methodparam">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

PharData::setMetadata

Sets phar archive meta-data

说明

public void PharData::setMetadata ( <span class="methodparam">mixed $metadata )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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

PharData::setSignatureAlgorithm

Set the signature algorithm for a phar and apply it

说明

public void PharData::setSignatureAlgorithm ( <span class="methodparam">int $sigtype )

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 <span class="classname">Phar 对象. 否则, 将抛出<span 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.

参数

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

返回值

没有返回值。

错误/异常

Throws UnexpectedValueException for many errors, BadMethodCallException if called for a zip- or a tar-based phar archive, and a <span class="classname">PharException if any problems occur flushing changes to disk.

参见

  • Phar::getSupportedSignatures
  • Phar::getSignature

PharData::setStub

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

说明

public bool PharData::setStub ( <span class="methodparam">string $stub [, int $len<span class="initializer"> = -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

参见

  • 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 <span class="ooclass"> extends SplFileInfo {

/* 方法 */

public void chmod ( <span class="type">int $permissions )

public bool compress ( <span class="methodparam">int $compression )

public <span class="methodname">__construct ( <span class="methodparam">string $entry )

public bool decompress ( <span class="methodparam">void )

public bool delMetadata ( <span class="methodparam">void )

public int <span class="methodname">getCRC32 ( <span class="methodparam">void )

public int <span class="methodname">getCompressedSize ( <span class="methodparam">void )

public string getContent ( <span class="methodparam">void )

public mixed getMetadata ( <span class="methodparam">void )

public int <span class="methodname">getPharFlags ( <span class="methodparam">void )

public bool hasMetadata ( <span class="methodparam">void )

public bool isCRCChecked ( <span class="methodparam">void )

public bool isCompressed ([ <span class="methodparam">int $compression_type = 9021976 ] )

public void setMetadata ( <span class="methodparam">mixed $metadata )

/* 继承的方法 */

public int <span class="methodname">SplFileInfo::getATime ( <span class="methodparam">void )

public string SplFileInfo::getBasename ([ <span class="methodparam">string $suffix ] )

public int <span class="methodname">SplFileInfo::getCTime ( <span class="methodparam">void )

public string SplFileInfo::getExtension ( <span class="methodparam">void )

public <span class="type">SplFileInfo <span class="methodname">SplFileInfo::getFileInfo ([ <span class="methodparam">string $class_name ] )

public string SplFileInfo::getFilename ( <span class="methodparam">void )

public int <span class="methodname">SplFileInfo::getGroup ( <span class="methodparam">void )

public int <span class="methodname">SplFileInfo::getInode ( <span class="methodparam">void )

public string SplFileInfo::getLinkTarget ( <span class="methodparam">void )

public int <span class="methodname">SplFileInfo::getMTime ( <span class="methodparam">void )

public int <span class="methodname">SplFileInfo::getOwner ( <span class="methodparam">void )

public string SplFileInfo::getPath ( <span class="methodparam">void )

public <span class="type">SplFileInfo <span class="methodname">SplFileInfo::getPathInfo ([ <span class="methodparam">string $class_name ] )

public string SplFileInfo::getPathname ( <span class="methodparam">void )

public int <span class="methodname">SplFileInfo::getPerms ( <span class="methodparam">void )

public string SplFileInfo::getRealPath ( <span class="methodparam">void )

public int <span class="methodname">SplFileInfo::getSize ( <span class="methodparam">void )

public string SplFileInfo::getType ( <span class="methodparam">void )

public bool SplFileInfo::isDir ( <span class="methodparam">void )

public bool SplFileInfo::isExecutable ( <span class="methodparam">void )

public bool SplFileInfo::isFile ( <span class="methodparam">void )

public bool SplFileInfo::isLink ( <span class="methodparam">void )

public bool SplFileInfo::isReadable ( <span class="methodparam">void )

public bool SplFileInfo::isWritable ( <span class="methodparam">void )

public <span class="type">SplFileObject <span class="methodname">SplFileInfo::openFile ([ <span class="methodparam">string $open_mode<span class="initializer"> = "r" [, <span class="methodparam">bool $use_include_path = false [, <span class="type">resource $context = null ]]] )

public void SplFileInfo::setFileClass ([ <span class="methodparam">string $class_name<span class="initializer"> = "SplFileObject" ] )

public void SplFileInfo::setInfoClass ([ <span class="methodparam">string $class_name<span class="initializer"> = "SplFileInfo" ] )

public string SplFileInfo::__toString ( <span class="methodparam">void )

}

PharFileInfo::chmod

Sets file-specific permission bits

说明

public void PharFileInfo::chmod ( <span class="methodparam">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 <span class="classname">Phar archive. Files within <span class="classname">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 ( <span class="methodparam">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 <span class="classname">Phar archive. Files within <span class="classname">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 <span class="methodname">PharFileInfo::__construct ( <span class="methodparam">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 <span class="classname">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 ( <span class="methodparam">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 <span class="classname">Phar archive. Files within <span class="classname">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 ( <span class="methodparam">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 <span class="classname">Phar archive. Files within <span class="classname">PharData archives do not have this restriction.

错误/异常

Throws PharException if errors occurred while flushing changes to disk, and <span class="classname">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 <span class="methodname">PharFileInfo::getCRC32 ( <span class="methodparam">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 <span class="methodname">PharFileInfo::getCompressedSize ( <span class="methodparam">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 <span class="function">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 ( <span class="methodparam">void )

This function behaves like <span class="function">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 ( <span class="methodparam">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 <span class="methodname">PharFileInfo::getPharFlags ( <span class="methodparam">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 ( <span class="methodparam">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 ( <span class="methodparam">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 ([ <span class="methodparam">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::setMetadata

Sets file-specific meta-data saved with a file

说明

public void PharFileInfo::setMetadata ( <span class="methodparam">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 <span class="function">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 <span class="classname">Phar archive. Files within <span class="classname">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

简介

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

类摘要

PharException

class PharException <span class="ooclass"> extends Exception {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string <span class="methodname">Exception::getMessage ( <span class="methodparam">void )

final public Throwable <span class="methodname">Exception::getPrevious ( <span class="methodparam">void )

final public mixed <span class="methodname">Exception::getCode ( <span class="methodparam">void )

final public string <span class="methodname">Exception::getFile ( <span class="methodparam">void )

final public int <span class="methodname">Exception::getLine ( <span class="methodparam">void )

final public array <span class="methodname">Exception::getTrace ( <span class="methodparam">void )

final public string <span class="methodname">Exception::getTraceAsString ( <span class="methodparam">void )

public string Exception::__toString ( <span class="methodparam">void )

final <span class="modifier">private void <span class="methodname">Exception::__clone ( <span class="methodparam">void )

}


本站为非盈利网站,作品由网友提供上传,如无意中有侵犯您的版权,请联系删除