PHP phar://


簡介

phar:// 流包裝器在 5.3.0 之後的 PHP 版本中均可用。Phar 的意思是 PHP 歸檔。它用於分發 PHP 應用程式或庫,並作為標準的 PHP 檔案執行。phar:// 包裝器支援使用 fopen() 開啟檔案進行讀取/寫入、重新命名以及目錄流操作 opendir() 以及建立和刪除目錄。

Phar 類允許將包含在目錄中的應用程式資源打包到 phar 歸檔檔案中。為了執行讀取操作,這個歸檔檔案被放置在 phar:// 包裝器中

構建 phar 歸檔檔案

首先,確保 php.ini 中的 phar.readonly 設定為 0。然後,建立一個名為 src 的資料夾,將應用程式的所有資源放入其中。建立 index.php 檔案

<?php
echo "phar application started";
?>

使用 Phar 類的物件來使用 buildFromDirectory() 方法構建包含 src 資料夾中檔案的 phar 歸檔檔案。將 index.php 指定為 setDefaultStub

<?php
// The php.ini setting phar.readonly must be set to 0
$pharFile = 'app.phar';
// clean up
if (file_exists($pharFile)) {
   unlink($pharFile);
}
if (file_exists($pharFile . '.gz')) {
   unlink($pharFile . '.gz');
}
// create phar
$p = new Phar($pharFile);
// creating our library using whole directory
$p->buildFromDirectory('src/');
// pointing main file which requires all classes
$p->setDefaultStub('index.php', '/index.php');
// plus - compressing it into gzip
$p->compress(Phar::GZ);
echo "$pharFile successfully created";
?>

從命令列執行上面的指令碼

php create-phar.php

這會在工作目錄中建立一個 app.phar。要執行 phar 歸檔,使用以下命令

php app.phar

使用 phar:// 包裝器

<?php
echo file_get_contents('phar://app.phar/index.php');
?>

這將顯示 index.php 檔案的內容

更新時間:2020-09-22

1K+ 瀏覽量

開啟你的 職業

完成課程獲得認證

開始
廣告