PHP development archive format phar file concept and usage
Jan 02, 2018 am 11:25 AMA 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. In order to achieve this, PHP uses the phar document file format. This concept is derived from the jar of java, 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.
There are three formats of phar archive files: tar archive, zip archive, and 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 added ArrayAccess object traversal using SPL 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 stream Streams, wrapper wrapper concepts and usage examples
Many PHP applications are distributed and run in phar format. The famous ones include dependency management: composer and unit testing: phpunit. Let's take a look at how to create, run, extract and restore.
Creation of phar file:
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
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()"; }
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>
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";
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()"; }
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 */ //產(chǎn)生一個yunke.phar文件 $phar = new Phar('yunke.phar', 0, 'yunke.phar'); // 添加project里面的所有文件到y(tǒng)unke.phar歸檔文件 $phar->buildFromDirectory(dirname(__FILE__)?.?'/project'); //設(shè)置執(zhí)行時的入口文件,第一個用于命令行,第二個用于瀏覽器訪問,這里都設(shè)置為index.php $phar->setDefaultStub('index.php',?'index.php');
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
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();
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";
If there is no second line, then yunke() on the third line will prompt that it is undefined, so it can be seen that when requiring a phar file, not all the files in it are imported, but only the entry execution file is imported. However, in actual projects, it is often Import other files that need to be used in this entry file. In this example, the entry execution file is project/index.php
Extraction and restoration of phar files:
Sometimes we are curious about the source code of the files contained in the phar. At this time, we need to restore the phar file. If we just have a look, we can use some IDE tools, such as phpstorm 10, you can open it directly. If you need to modify it, you need to extract it. For demonstration, we download a composer.phar and put it in the server directory, and create a get.php file in the root directory. The content is as follows:
<?php /** * Created by yunke. * User: yunke * Date: 2017/2/9 * Time: 19:02 */ $phar = new Phar('composer.phar'); $phar->extractTo('composer');?//提取一份原項目文件 $phar->convertToData(Phar::ZIP);?//另外再提取一份,和上行二選一即可
Use a browser to access this file to extract it. The above example shows two extraction methods: the second line will create a composer directory and put the extracted content into it. The third line will generate a composer.zip file, which can be decompressed. Extracted and restored project files are available.
Replenish:
1. When deploying the phar file to the production server, you need to adjust the server configuration to avoid the browser directly downloading the phar file when accessed
2. You can set an alias for the archive. The alias is saved permanently in the archive file. It can refer to the archive with a short name regardless of where the archive file is stored in the file system. Set the alias:
$phar?=?new?Phar('lib/yunke.phar',?0); $phar->setAlias?(?"yun.phar");
After setting the alias, you can use it as follows:
<?php require?"lib/yunke.phar"; require?"phar://yun.phar/Lib.php";?//使用別名訪問歸檔文件 require?"phar://lib/yunke.phar/Lib.php";?//當(dāng)然仍然可以使用這樣的方式去引用
If you do not specify an alias when making a phar file, you can also use Phar::mapPhar('yunke.phar'); to specify it in the stub file
3. There is a stub file in the archive file, which is actually a piece of PHP execution code. It can be set when making the archive. When the archive file is executed directly, it is actually executed, so it is a startup file; when the archive file is included in the script, it is like Include it and run it just like a normal php file, but the stub code will not be executed when you directly include a file in the archive using phar://. The stub file often requires other files to be run. The restriction on the stub file is only to end with __HALT_COMPILER();. The default stub is designed to run without the phar extension. It extracts the contents of the phar file into a temporary Directory and then execute, but starting from php5.3, the extension is enabled by default
4. The created phar file cannot be modified, so files such as configuration files need to be placed outside the archive file
5. mapPhar function: This function should only be called in the stub code. When the archive alias is not set, it can be used to set the alias and open a reference mapped to the phar stream.
Related recommendations:
How to use the archive format phar for PHP development
How to use the phar package PHP
Detailed tutorial on using phar package in php
The above is the detailed content of PHP development archive format phar file concept and usage. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
