PHP 8.3.4 Released!

Phar::buildFromDirectory

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::buildFromDirectoryディレクトリ内のファイルから phar を作成する

説明

public Phar::buildFromDirectory(string $directory, string $pattern = ""): array

注意:

このメソッドは、php.iniphar.readonly0 でないと Phar オブジェクトで動作しません。それ以外の場合は PharException がスローされます。

ディレクトリの中身をもとに phar アーカイブを作成します。 オプションの 2 番目のパラメータで正規表現 (pcre) を指定すると、特定のファイルを除外することができます。 正規表現にマッチするすべてのファイルがアーカイブに含められ、 それ以外のファイルは除外されます。より詳細に制御するには Phar::buildFromIterator() を使用します。

パラメータ

directory

アーカイブに追加するすべてのファイルを含むディレクトリへの フルパスあるいは相対パス。

pattern

オプションで指定する pcre 正規表現。 これを使用してファイル一覧をフィルタリングします。 正規表現にマッチするファイルパスのみがアーカイブに追加されます。

戻り値

Phar::buildFromDirectory() は、連想配列を返します。これは、 ファイルの内部パスをファイルシステム上のフルパスを対応させたものです。

エラー / 例外

このメソッドは、内部ディレクトリイテレータのインスタンスの作成に失敗したときに BadMethodCallException をスローします。 また、phar アーカイブの保存時にエラーが発生した場合は PharException をスローします。

変更履歴

バージョン 説明
8.1.0 Phar::buildFromDirectory() は、 false を返さなくなりました。

例1 Phar::buildFromDirectory() の例

<?php
// "project.phar" というエイリアスで作成します
$phar = new Phar('project.phar', 0, 'project.phar');
// project 内のすべてのファイルを追加します
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// project 内のファイルのうち、php ファイルだけを追加します
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

参考

add a note

User Contributed Notes 1 note

up
6
dalfarra at codref dot com
6 years ago
If you want to exclude a directory from the archive (but include all the other content), the regular expression must take into consideration the whole path of the file, not just the file or directory name relative to the source folder.

As an example, if we want to exclude "nbproject" directory from the archive (and any occurrence of it):

/tmp/myfolder
/nbproject
/something
/something-else
/nbproject
/file1.php
/file2.php

the regex should be:
<?php
$exclude
= '/^(?!(.*nbproject))(.*)$/i'; //ignoring the case
?>

A more complete example:
<?php
$archive_file
= 'myarchive.tar';
$folder_to_compress = '/tmp/myfolder';
$archive = new PharData($archive_file);
$exclude = '/^(?!(.*nbproject))(.*)$/i';
$archive->buildFromDirectory($folder_to_compress,$exclude);
$archive->compress(Phar::GZ);
unlink($archive_file); // as we already obtained a tar.gz
?>

the archive will contain:
/
/something
/something-else
/file1.php
/file2.php
To Top