function makePhar(array $dt) { //retornando com erro se o array estiver vazio if (count($dt) <= 0) { return false; } //aumentando a memoria e o tempo de execução - pode ser muito significante em sistemas lentos e diretórios muito grandes ini_set('memory_limit', '30M'); ini_set('max_execution_time', 180); //Array com os dados da execução $ok = array(); //lendo e executando as conversões indicadas foreach ($dt as $k => $lote) { //checando se deve converter indice['r'] if (!isset($lote['r'])) { continue; } $dir = trim($lote['o'], ' \\/'); $stub = '<?php Phar::interceptFileFuncs(); Phar::mungServer(array(\'REQUEST_URI\', \'PHP_SELF\', \'SCRIPT_NAME\', \'SCRIPT_FILENAME\')); Phar::webPhar(\'\', \'\', \'404.php\'); __HALT_COMPILER();'; // include(\'phar://\' . __FILE__ . \'/' . $lote['i'] . '\'); if (is_dir($dir)) { //criando arquivo PHAR $phar = new Phar(trim($lote['d'], ' \\/')); //pegando o diretório (e sub-diretórios) e arquivos contidos $phar->buildFromIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)), $dir); //criando o cabeçalho Stub $phar->setStub($stub); //carregando a assinatura if (file_exists(LIB . 'key.md5')) { $phar->setSignatureAlgorithm(Phar::MD5, file_get_contents(LIB . 'key.md5')); } //comprimindo os dados (exceto o Stub) $compactar = false; if (isset($lote['z'])) { $compactar = true; if (Phar::canCompress(Phar::GZ)) { $phar->compressFiles(Phar::GZ); } elseif (Phar::canCompress(Phar::BZ2)) { $phar->compressFiles(Phar::BZ2); } } //adicionando os dados de saída $ok[$k] = array('o' => $dir, 'd' => $lote['d'], 'z' => $compactar, 'i' => $lote['i']); } else { $ok[$k] = array('e' => 'O diretório "' . $dir . '" não existe!'); } } if (count($ok) == 0) { return false; } return $ok; }
/** * Add compress to phar file. * * @param \Phar $phar PHAR object to update. * @param int[] $configuration List of compress types. * * @throws \yii\base\InvalidConfigException On wrong compress type set (index0h\phar\Module::compress). */ public static function addCompress(\Phar $phar, $configuration) { if ($configuration === false) { return; } echo "\nAdd compress"; foreach ($configuration as $compress) { if (in_array($compress, [\Phar::NONE, \Phar::GZ, \Phar::BZ2], true) === false) { throw new InvalidConfigException("Invalid configuration. Unknown compress type '{$compress}'."); } if (\Phar::canCompress($compress) === true) { $phar->compress($compress); } } }
public static function convertVendorsToPhar(Event $event) { $vendorDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'vendor'; $phars = []; echo "Converting vendor package dirs to phar...\n"; foreach (new \DirectoryIterator($vendorDir) as $dir) { if (in_array($dir->getFilename(), ['..', '.', 'composer']) || !$dir->isDir()) { continue; } foreach (new \DirectoryIterator($dir->getRealPath()) as $subDir) { if (in_array($subDir->getFilename(), ['..', '.']) || !$subDir->isDir()) { continue; } echo "... " . $dir->getFilename() . '/' . $subDir->getFilename() . "\n"; $fName = $subDir->getRealPath() . '.phar'; $fNameTmp = $fName . '.tmp'; $phar = new \Phar($fNameTmp); $phar->buildFromDirectory($subDir->getRealPath(), '#\\.(?!git)#'); if (\Phar::canCompress(\Phar::GZ)) { $phar->compressFiles(\Phar::GZ); } else { if (\Phar::canCompress(\Phar::BZ2)) { $phar->compressFiles(\Phar::BZ2); } } if (file_exists($fName)) { unlink($fName); } unset($phar); rename($fNameTmp, $fName); //delDirTree($subDir->getRealPath()); $phars[$dir->getFilename() . '/' . $subDir->getFilename()] = str_replace(DIRECTORY_SEPARATOR, '/', str_replace($vendorDir, '', $fName)); } } echo "\nConverting autoload files: \n"; $autoloadFiles = ['composer/autoload_classmap.php', 'composer/autoload_files.php', 'composer/autoload_namespaces.php', 'composer/autoload_psr4.php']; foreach ($autoloadFiles as $file) { echo $file . "\n"; $filePath = $vendorDir . DIRECTORY_SEPARATOR . $file; $content = file_get_contents($filePath); $content = preg_replace('#(?<!\'phar://\' . )\\$vendorDir\\s+.\\s+\'(/[-\\w\\d_]+/[-\\w\\d_]+)#', '\'phar://\' . $vendorDir . \'$1.phar', $content); if ($content) { file_put_contents($filePath, $content); } } echo "\nComplete!\n"; }
<?php //include 'phar://dd.phar'; try { // open an existing phar $p = new Phar('dd.phar', 0); // Phar extends SPL's DirectoryIterator class foreach (new RecursiveIteratorIterator($p) as $file) { // $file is a PharFileInfo class, and inherits from SplFileInfo echo $file->getFileName() . "\n"; echo file_get_contents($file->getPathName()) . "\n"; // display contents; if (Phar::canCompress(Phar::GZ)) { $p[$file->getFileName()]->compress(Phar::GZ); } } } catch (Exception $e) { echo 'Could not open Phar: ', $e; } echo "test"; // TODO: Is this right?? //??%?( $Cities = array(1 => 'London', 2 => 'Toronto', 3 => 'Warsaw'); class MyClass { public static $var; public static function f() { } } //MyClass::
<?php if (!class_exists('Phar')) { die('Class Phar not found.'); } if (is_file('wasp.phar')) { unlink('wasp.phar'); } $arj = new Phar('wasp.phar'); $arj->setStub('<?php define( \'CORE_PATH\', \'phar://\' . __FILE__ ); require( CORE_PATH . \'/bootstrap.php\' ); __HALT_COMPILER(); ?>'); $arj->buildFromDirectory('wasp/'); $arj->setSignatureAlgorithm(PHAR::MD5); if (Phar::canCompress(Phar::GZ)) { $arj->compressFiles(Phar::GZ); } else { if (Phar::canCompress(Phar::BZ2)) { $arj->compressFiles(Phar::BZ2); } } echo 'wasp.phar created!';
public function downloadnotgifAction() { $order_id = $this->getRequest()->getParam('order_id'); $shipment_id = $this->getRequest()->getParam('shipment_id'); $label_id = $this->getRequest()->getParam('label_id'); $type = $this->getRequest()->getParam('type'); $path = Mage::getBaseDir('media') . DS . 'upslabel' . DS . 'label' . DS; $upslabel = Mage::getModel('upslabel/upslabel'); if (!isset($label_id) || empty($label_id) || $label_id <= 0) { $colls2 = $upslabel->getCollection()->addFieldToFilter('order_id', $order_id)->addFieldToFilter('shipment_id', $shipment_id)->addFieldToFilter('type', $type)->addFieldToFilter('status', 0); if (extension_loaded('zip')) { $zip = new ZipArchive(); $zip_name = sys_get_temp_dir() . DS . 'order' . $order_id . 'shipment' . $shipment_id . '.zip'; if ($zip->open($zip_name, ZIPARCHIVE::CREATE) !== TRUE) { } foreach ($colls2 as $coll) { if (file_exists($path . $coll->getLabelname()) && $coll->getTypePrint() != 'GIF') { $zip->addFile($path . $coll->getLabelname(), $coll->getLabelname()); } } $zip->close(); if (file_exists($zip_name)) { header('Content-type: application/zip'); header('Content-Disposition: attachment; filename="labels_order' . $order_id . '_shipment' . $shipment_id . '.zip"'); readfile($zip_name); unlink($zip_name); } } else { $phar = new Phar(sys_get_temp_dir() . DS . 'order' . $order_id . 'shipment' . $shipment_id . '.phar'); $phar = $phar->convertToExecutable(Phar::ZIP); $applicationType = 'zip'; foreach ($colls2 as $coll) { if (file_exists($path . $coll->getLabelname()) && $coll->getTypePrint() != 'GIF') { if ($data = file_get_contents($path . $coll->getLabelname())) { $phar[$coll->getLabelname()] = $data; } } } if (Phar::canCompress(Phar::GZ)) { $phar->compress(Phar::GZ, '.gz'); $applicationType = 'x-gzip'; } if (file_exists($phar::running(false))) { $pdfData = file_get_contents($phar::running(false)); @unlink($phar::running(false)); header("Content-Disposition: inline; filename=labels_order' . {$order_id} . '_shipment' . {$shipment_id} . '.zip"); header("Content-type: application/" . $applicationType); echo $pdfData; } } } return true; }
<?php var_dump(Phar::canCompress(Phar::GZ) == extension_loaded("zlib")); var_dump(Phar::canCompress(Phar::BZ2) == extension_loaded("bz2")); ?> ===DONE===
<?php ini_set('phar.readonly', 1); function print_exception($e) { echo "\nException: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine() . "\n"; } Phar::mungServer('hi'); Phar::createDefaultStub(array()); Phar::loadPhar(array()); Phar::canCompress('hi'); try { $a = new Phar(array()); } catch (TypeError $e) { print_exception($e); } try { $a = new Phar(dirname(__FILE__) . '/files/frontcontroller10.phar'); } catch (PharException $e) { print_exception($e); } $a->convertToExecutable(array()); $a->convertToData(array()); try { $b = new PharData(dirname(__FILE__) . '/whatever.tar'); } catch (PharException $e) { print_exception($e); } try { $c = new PharData(dirname(__FILE__) . '/whatever.zip'); } catch (PharException $e) {
<?php ## Сжатие архива. try { $phar = new Phar('compress.phar', 0, 'compress.phar'); if (Phar::canWrite() && Phar::canCompress()) { $phar->startBuffering(); foreach (glob('../composer/photos/*') as $jpg) { $phar[basename($jpg)] = file_get_contents($jpg); } // Назначаем файл-заглушку $phar['show.php'] = file_get_contents('show.php'); $phar->setDefaultStub('show.php', 'show.php'); // Сжимаем файл $phar->compress(Phar::GZ); $phar->stopBuffering(); } else { echo 'PHAR-архив не может быть бы записан'; } } catch (Exception $e) { echo 'Невозможно открыть PHAR-архив: ', $e; }
function package($source = null) { $con = \cherry\cli\Console::getAdapter(); if (!$source) { $con->write("You need to at least specify the source path.\n"); return 1; } $opts = func_get_args(); $opts = array_slice($opts, 1); $loader = null; $compress = null; $includelib = false; $dest = $source . '.phar'; $isExtension = false; for ($optidx = 0; $optidx < count($opts); $optidx++) { $opt = $opts[$optidx]; if ($optidx < count($opts) - 1) { $optarg = $opts[$optidx + 1]; } else { $optarg = null; } switch ($opt) { case '+template': $tools = true; break; case 'with-stub': $loader = $optarg; $optidx++; break; case 'to': $dest = $optarg; $optidx++; break; case 'compress': $compress = $optarg; $optidx++; break; case '+extension': $isExtension = true; break; case '+standalone': $includelib = true; break; default: $con->write("Unknown argument: %s\n", $opt); return 1; } } $con->write('Scanning %s... ', $source); $appcfg = null; $extcfg = null; $itfile = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \FilesystemIterator::SKIP_DOTS)); $files = array(); foreach ($itfile as $file) { $fn = $file->__toString(); if (basename($fn) == 'application.ini') { $appcfg = parse_ini_file($fn, true); } if (basename($fn) == 'extension.ini') { $isExtension = true; } $files[] = $fn; } if ($isExtension && !file_exists($source . '/extension.ini')) { $con->warn("Error: This doesn't seem to be an extension.\n"); return 1; } if ($isExtension) { $ext = parse_ini_file($source . '/extension.ini', true); $meta = $ext['extension']; $meta['type'] = 'extension'; } elseif (!empty($appcfg)) { $meta = $appcfg['application']; $meta['type'] = 'application'; } else { $con->warn("Warning: Directory does not appear to contain neither an application or an extension\n"); $meta = array('name' => 'Unknown Application', 'version' => '?.?', 'type' => 'archive'); } $con->write("%s, %d files\n", $meta['type'], count($files)); if (!empty($appcfg)) { $aname = empty($appcfg['application']['name']) ? 'Unknown application' : $appcfg['application']['name']; $aver = empty($appcfg['application']['version']) ? '(Unknown version)' : $appcfg['application']['version']; $webindex = '/public/'; $con->write("Preparing to archive %s %s\n", $aname, $aver); } $cliloader = empty($appcfg['application']['loader']) ? 'loader.php' : $appcfg['application']['loader']; $webroot = empty($appcfg['application']['webroot']) ? '/public/' : $appcfg['application']['webroot']; $meta['loader'] = $cliloader; if ($compress == 'bz2') { if (substr($dest, -4, 4) != '.bz2') { $dest .= '.bz2'; } } elseif ($compress == 'gzip') { if (substr($dest, -3, 3) != '.gz') { $dest .= '.gz'; } } elseif ($compress == null) { } else { $con->write("Unknown compression: %s\n", $compress); } $con->write("Cleaning up temporary files...\n"); if (file_exists($dest)) { unlink($dest); } $phar = new \Phar($dest); if ($phar->canCompress() && $compress) { if ($compress == 'bz2') { $phar->compress(\Phar::BZ2); } elseif ($compress == 'gzip') { $phar->compress(\Phar::GZIP); } else { $con->write("Unknown compression: %s\n", $compress); } } $con->write("Creating package...\n"); foreach ($files as $file) { $phar->addFile($file, str_replace($source, '', $file)); } if ($loader) { $loaderpath = CHERRY_LIB . '/share/stubs'; $loadercfg = parse_ini_file($loaderpath . DIRECTORY_SEPARATOR . $loader . '.ini', true); if (!file_exists($loaderpath . DIRECTORY_SEPARATOR . $loader . '.ini')) { $con->write("Stub not found. Try list-stubs to find the available stubs\n"); return 1; } $con->write("Embedding loader stub...\n"); if (file_exists($loaderpath . DIRECTORY_SEPARATOR . $loader . '.stub')) { $loaderstub = @file_get_contents($loaderpath . DIRECTORY_SEPARATOR . $loader . '.stub'); } else { $loaderstub = ''; } if (!empty($loadercfg['stub']['defaultstub']) && $loadercfg['stub']['defaultstub']) { $loaderstub .= \Phar::createDefaultStub($cliloader, $webroot); } $phar->setStub($loaderstub); } $phar->addFromString('manifest.json', json_encode($meta)); $con->write("Done\n"); }
} } } } if (file_exists($argv[2])) { if (file_exists($file)) { @unlink($file); echo "Overwritting phar..."; } else { echo "Creating phar..."; } $phar = new Phar(getcwd() . "/" . $file, 0, $file); //Check compression if ($compression != null) { if ($compression == Phar::GZ) { if ($phar->canCompress(Phar::GZ)) { $phar->compress($compression); echo "\nCompression set to GZIP"; } else { echo "\nCan't use GZIP compression"; } } elseif ($compression == Phar::BZ2) { if ($phar->canCompress(Phar::BZ2)) { $phar->compress($compression); echo "\nCompression set to BZIP2"; } else { echo "\nCan't use BZIP2 compression"; } } } //Check metadata
/** * Check if compression is available * * @return boolean */ public static function canCompress() { return \Phar::canCompress(self::COMPRESSION_TYPE); }
<?php /* check this works and actually returns the boolean value */ var_dump(Phar::canCompress() == (extension_loaded("zlib") || extension_loaded("bz2")));
path to the PF framework, set it as "phar://PF". */ // Configuration: $dir = __DIR__; ini_set("phar.readonly", 0); // Could be done in php.ini #$path = $dir.'/yf'; $path = "/home/www/yf/"; $name = 'yf.phar'; echo $name; $mode = Phar::GZ; // Error checks: if (!class_exists('Phar')) { die('*** Phar extension is not installed (or not enabled)'); } if (!Phar::canCompress($mode)) { die('*** Compression unsupported - please enable the zlib extension'); } if (!is_dir($path)) { die('*** PF Framework not found: ' . $path); } if (!Phar::canWrite()) { die('*** Phar is in read-only mode (check phar.readonly in php.ini)'); } // Iterator: class FrameworkIterator implements Iterator, Countable { private $index; private $files; private $baselen; private $size;
<?php echo "Creating the .phar<br/>\n"; $phar = new Phar('eP6RESTclient.phar'); echo "Adding all files<br/>\n"; $phar->buildFromDirectory('../src'); echo "Create and set default stub<br/>\n"; $phar->createDefaultStub('src/Shop.class.php'); $phar->setDefaultStub(); if (Phar::canCompress()) { echo "Create compressed .gz file<br/>\n"; $phar->compress(Phar::GZ); echo "Create compressed .bz2 file"; $phar->compress(Phar::BZ2); }