Home Backend Development PHP Tutorial How PHP operates phar files

How PHP operates phar files

Apr 11, 2018 am 09:47 AM
phar php document

This time I will show you how to operate phar files with PHP. What are the precautions for operating phar files with PHP? The following is a practical case, let's take a look.

This article describes the concept and usage of the archive format phar file in PHP development. Share it with everyone for your reference, the details are as follows:

A PHP application is often composed of multiple files. It is very convenient if they can be concentrated into one file to distribute and run. There are many such examples, such as the installation program on the window operating system, a jquery library, etc. Etc., in order to achieve this, PHP uses the phar document file format. This concept is derived from Java's jar, but it is mainly designed for PHP's web environment, unlike JAR archives, Phar archives can be Handled natively, so no additional tools are needed to create or use it, just use a php script to create or extract it. phar is a compound word composed of PHP and Archive composition, you can see that it means php archive file.

For the official website documentation of phar, please see http://php.net/manual/zh/book.phar.php. This document can be seen as complementary to the official website documentation

There are three formats of phar archive files: tar archive, zip archive, phar archive . The first two types of execution require Phar to install Phar extension support, and are rarely used. Here we mainly talk about the phar archive format.

The phar format archive file can be executed directly. Its generation relies on the Phar extension and is generated by a php script written by yourself.

The Phar extension is not a new concept to PHP. It has been built into PHP in php5.3. It was originally written in PHP and named PHP_Archive was then added to the PEAR library in 2005. Since pure PHP solutions to this problem are very slow in practice, 2007 Rewritten as a pure C language extension, and adding ArrayAccess using SPL

Object traversal Phar Archiving support. Since then, a lot of work has been done to improve the performance of Phar archives.

The Phar extension depends on the php stream wrapper. For this, please refer to the previous article PHP Streams and wrapper wrapper concepts and usage examples for detailed explanation

Many PHP applications are distributed and run in phar format. The famous ones include dependency management: composer,

Unit test:phpunit. Let's take a look at how to create, run, extract and restore.

Creation of phar files:

First modify the phar.readonly option in php.ini, remove the preceding semicolon, and change the value to off. Due to security reasons, this option defaults to on. If it is disabled in php.ini (the value is 0 or off) , then it can be turned on or off in the user script. If it is turned on in php.ini, the user script cannot be turned off, so it is set to off here to show the example.

Let's create a project. Create a project folder in the server root directory as project. The structure in the directory is as follows:

file
  -yunek.js
  -yunke.css
lib
  -lib_a.php
template
  -msg.html
index.php
Lib.php
Copy after login
The file folder has two js and css files with empty contents. It only demonstrates that phar can contain multiple file formats

The content of lib_a.php is as follows:

<?php
/**
 * Created by yunke.
 * User: yunke
 * Date: 2017/2/10
 * Time: 9:23
 */
function show(){
  echo "l am show()";
}
Copy after login

The content of msg.html is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>phar</title>
</head>
<body>
<?=$str; ?>
</body>
</html>
Copy after login
The content of index.php is as follows:

<?php
/**
 * Created by yunke.
 * User: yunke
 * Date: 2017/2/10
 * Time: 9:17
 */
require "lib/lib_a.php";
show();
$str = isset($_GET["str"]) ? $_GET["str"] : "hello world";
include "template/msg.html";
Copy after login

The content of Lib.php is as follows:

<?php
/**
 * Created by yunke.
 * User: yunke
 * Date: 2017/2/10
 * Time: 9:20
 */
function yunke()
{
  echo "l am yunke()";
}
Copy after login

The project file is ready and started to be created. Now create a yunkeBuild.php in the same directory as the project folder to generate a phar format file. The content is as follows:

<?php
/**
 * Created by yunke.
 * User: yunke
 * Date: 2017/2/10
 * Time: 9:36
 */
//产生一个yunke.phar文件
$phar = new Phar(&#39;yunke.phar&#39;, 0, &#39;yunke.phar&#39;);
// 添加project里面的所有文件到yunke.phar归档文件
$phar->buildFromDirectory(dirname(FILE) . '/project');
//设置执行时的入口文件,第一个用于命令行,第二个用于浏览器访问,这里都设置为index.php
$phar->setDefaultStub('index.php', 'index.php');
Copy after login
Then access this yunkeBuild.php file in the browser, a yunke.phar file will be generated. At this time, the server root

directory structure is as follows:

project
yunkeBuild.php
yunke.phar
Copy after login
This is the simplest process to generate a phar archive file. For more information, please see the official website. It should be noted here that if the project does not have a single execution entry, it is not appropriate to use the phar archive file

Usage of phar archive files:

We create an index.php file in the server root directory to demonstrate how to use the phar file created above. The content is as follows:

<?php
/**
 * Created by yunke.
 * User: yunke
 * Date: 2017/2/8
 * Time: 9:33
 */
require "yunke.phar";
require "phar://yunke.phar/Lib.php";
yunke();
Copy after login

If there is only the first line in the index.php file, then add the following code exactly the same as when not using an archive file:

require "project/index.php";
Copy after login

如果没有第二行,那么第三行的yunke()将提示未定义,所以可见require一个phar文件时并不是导入了里面所有的文件,而只是导入了入口执行文件而已,但在实际项目中往往在这个入口文件里导入其他需要使用的文件,在本例中入口执行文件为project/index.php

phar文件的提取还原:

我们有时候会好奇phar里面包含的文件源码,这个时候就需要将phar文件还原,如果只是看一看的话可以使用一些ide工具,比如phpstorm 10就能直接打开它,如果需要修改那么就需要提取操作了,为了演示,我们下载一个composer.phar放在服务器目录,在根目录建立一个get.php文件,内容如下:

<?php
/**
 * Created by yunke.
 * User: yunke
 * Date: 2017/2/9
 * Time: 19:02
 */
$phar = new Phar(&#39;composer.phar&#39;);
$phar->extractTo('composer'); //提取一份原项目文件
$phar->convertToData(Phar::ZIP); //另外再提取一份,和上行二选一即可
Copy after login

用浏览器访问这个文件,即可提取出来,以上列子展示了两种提取方式:第二行将建立一个composer目录,并将提取出来的内容放入,第三行将产生一个composer.zip文件,解压即可得到提取还原的项目文件。

补充:

1、在部署phar文件到生产服务器时需要调整服务器的配置,避免当访问时浏览器直接下载phar文件

2、可以为归档设置别名,别名保存在归档文件中永久保存,它可以用一个简短的名字引用归档,而不管归档文件在文件系统中存储在那里,设置别名:

$phar = new Phar('lib/yunke.phar', 0);
$phar->setAlias ( "yun.phar");
Copy after login

设置别名后可以如下使用:

<?php
require "lib/yunke.phar";
require "phar://yun.phar/Lib.php"; //使用别名访问归档文件
require "phar://lib/yunke.phar/Lib.php"; //当然仍然可以使用这样的方式去引用
Copy after login

如果在制作phar文件时没有指定别名,也可以在存根文件里面使用Phar::mapPhar('yunke.phar');指定

3、归档文件中有一个存根文件,其实就是一段php执行代码,在制作归档时可以设置,直接执行归档文件时,其实就是执行它,所以它是启动文件;在脚本中包含归档文件时就像包含普通php文件一样包含它并运行,但直接以phar://的方式包含归档中某一个文件时不会执行存根代码, 往往在存根文件里面require包含要运行的其他文件,对存根文件的限制仅为以HALT_COMPILER();结束,默认的存根设计是为在没有phar扩展时能够运行,它提取phar文件内容到一个临时目录再执行,不过从php5.3开始该扩展默认内置启用了

4、制作的phar文件不能被改动,因此配置文件之类的文件需要另外放置在归档文件外面

5、mapPhar函数:这个函数只应该在stub存根代码中调用,在没有设置归档别名的时候可以用来设置别名,打开一个引用映射到phar流

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何用swoole与websocket开发一个聊天室

在PHP中怎样实现微信退款功能

The above is the detailed content of How PHP operates phar files. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles