Table of Contents
If the initial file is too large or the content has been changed too much
How to detect changes in file size
Code implementation
The following are the results
Home Backend Development PHP Problem How to implement linux commands in php

How to implement linux commands in php

Dec 08, 2021 am 11:00 AM
linux php

php method to implement linux commands: 1. Create a PHP sample file; 2. Enter "#!/usr/bin/env php" on the first line; 3. Pass "if(2 != count ($argv)){...}" and other codes can implement the Linux command "tail -f".

How to implement linux commands in php

The operating environment of this article: linux5.9.8 system, PHP version 7.1, Dell G3 computer.

How does php implement linux commands?

PHP implements linux commandstail -f

Suddenly today Thinking of a question someone asked me before, how to implement the command tail -f in Linux through PHP, let me analyze and implement it here.

This is quite simple when you think about it. It detects the file through a loop to see if the size of the file has changed. If there is a change, output the changed part of the file. Of course, there will be a lot of details in it. Here is a detailed analysis. Down.

If the initial file is too large or the content has been changed too much

At this time, a lot of content is output at once and may not be visible clearly, so I set a threshold here8192, when the content When the length exceeds this threshold, only the last 8192 bytes will be output, so that there will be no problem of unclear visibility due to large area refresh.

How to detect changes in file size

This question is the core of this program. Whether it can succeed or not depends on this part of the performance.
My implementation here is as follows:

  • Open the file handle$fp. Please note that the file handle here needs to be opened and closed only once in the whole process. So put it outside the loop.
  • Initialize the current file size file_size and file_size_new to 0.
    • Update in the loopfile_size_newFile size, please note here that before getting the file size in php, you must run the function clearstatcache() to clear the file status cache, otherwise get File sizes may vary.
    • Calculate add_size = file_size_new - file_size to see if the file size changes. If so, move the file pointer to the specified position, then output the newly added content and update file_size The value is new_file_size.
    • usleep(50000), sleep for 1/20 seconds.

Code implementation

#!/usr/bin/env php 
<?php
if(2 != count($argv)){
    fwrite(
        STDERR,
        "调用格式错误!使用格式 ./tail filename".PHP_EOL
    );  
    return 1;
}

$file_name      = $argv[1];
define("MAX_SHOW", 8192);

$file_size      = 0;
$file_size_new  = 0;
$add_size       = 0;
$ignore_size    = 0;
$fp = fopen($file_name, "r");
while(1){
    clearstatcache();
    $file_size_new  = filesize($file_name);
    $add_size       = $file_size_new - $file_size;
    if($add_size > 0){ 
        if($add_size > MAX_SHOW){
            $ignore_size    = $add_size - MAX_SHOW;
            $add_size       = MAX_SHOW;
            fseek($fp, $file_size + $ignore_size);
        }   
        fwrite(
            STDOUT,
            fread($fp, $add_size)
        );  
        $file_size  = $file_size_new;
    }
    usleep(50000);
}

fclose($fp);
Copy after login

Code implementation#!/usr/bin/env php in the first line here tells the executable Files and executable files php are searched in the system PATH. The advantage of this is that it has good portability.

2016-02-22 11:28:51Improvement

I checked the PHP official manual, the fseek function can be improved here, this function It also accepts a third parameter, indicating the type of offset pointer. The default is SEEK_SET, which is the offset from the beginning. It can also be set to SEEK_CUR, which indicates the offset from the current position, so here Change to fseek($fp, $ignore_size, $ignore_size);

The following are the results

Recommended study: "PHP video tutorial

The above is the detailed content of How to implement linux commands in php. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

BITGet official website installation (2025 beginner's guide) BITGet official website installation (2025 beginner's guide) Feb 21, 2025 pm 08:42 PM

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Apr 01, 2025 pm 03:06 PM

Causes and solutions for errors when using PECL to install extensions in Docker environment When using Docker environment, we often encounter some headaches...

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.

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,

How to efficiently integrate Node.js or Python services under LAMP architecture? How to efficiently integrate Node.js or Python services under LAMP architecture? Apr 01, 2025 pm 02:48 PM

Many website developers face the problem of integrating Node.js or Python services under the LAMP architecture: the existing LAMP (Linux Apache MySQL PHP) architecture website needs...

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

See all articles