2024 年日本 PHP 研討會

使用 Phar 封存:phar 資料流包裝器

Phar 資料流包裝器完全支援 fopen() 讀取和寫入(非附加), unlink(), stat(), fstat(), fseek(), rename() 以及目錄資料流操作 opendir()rmdir()mkdir()

也可以使用資料流上下文在 Phar 封存中操作個別檔案壓縮和每個檔案的後設資料。

<?php
$context
= stream_context_create(array('phar' =>
array(
'compress' => Phar::GZ)),
array(
'metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?>

即使 allow_url_fopenallow_url_include INI 選項被禁用,phar 資料流包裝器仍可運作,因為它不作用於遠端檔案,也不能作用於遠端檔案。

雖然可以僅使用資料流操作從頭開始創建 phar 封存檔,但最好使用 Phar 類別內建的功能。資料流包裝器最適合用於唯讀操作。

新增筆記

使用者貢獻的筆記 2 則筆記

staff at pro-unreal dot de
13 年前
請注意,phar 資料流包裝器不適用於任何 glob。
當您決定將專案移至 phar 封存檔時,需要考慮這一點。

以下程式碼將無法運作
<?php
glob
('phar://some.phar/*');
new
DirectoryIterator('glob://phar://some.phar/*');
?>

而以下程式碼將可以運作
<?php
new DirectoryIterator('phar://some.phar/');
?>
carl at dot dot com
13 年前
一些關於如何使用資料流包裝器的範例將會非常有幫助。
我摸索的嘗試只發現了以下內容

<?php
$p
= new PharData(dirname(__FILE__).'/phartest.zip', 0,'phartest',Phar::ZIP) ;

$p->addFromString('testfile.txt',
'this is just some test text');

// 可以正常運作
echo file_get_contents('phar://phartest.zip/testfile.txt');

// 無法正常運作
file_put_contents('phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt');

$context = stream_context_create(
array(
'phar' =>array('compress' =>Phar::ZIP))
) ;

// 無法正常運作
file_put_contents(
'phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt',0,$context);

// 只能以 'r' 唯讀模式正常運作。
$f = fopen(
'phar://C:\\Inetpub\\wwwroot\\PACT\\test\\phartest.zip\\testfile.txt',
'r') ;
?>
To Top