Home Backend Development PHP Tutorial How to batch process files in Linux via PHP script

How to batch process files in Linux via PHP script

Oct 05, 2023 pm 12:03 PM
php linux File processing

How to batch process files in Linux via PHP script

How to batch process files in Linux through PHP script

Overview:
In the Linux environment, batch processing of files is a common requirement. This task can be accomplished quickly and efficiently using PHP scripts. This article will introduce how to batch process files in Linux through PHP scripts and provide relevant code examples.

Steps:

  1. Make sure PHP is installed:
    To use PHP scripts to process files in Linux, you first need to make sure PHP is installed in the system. You can check the PHP version information by typing php -v on the command line.
  2. Create a PHP script:
    To create a new PHP script file in Linux, you can use the following command:

    $ touch file_processing.php
  3. Edit the script file:
    Use a text editor (such as nano, vim, etc.) to open the script file you just created and add the following basic code structure:

    <?php
    // 在这里编写代码逻辑
    ?>
  4. Set the folder path:
    In Before you start writing specific logic, you need to set the folder path to be processed. You can use the getcwd() function to get the absolute path of the current working directory, or manually specify a path. The following example is to manually specify the path:

    $directory = '/var/www/html/files'; // 文件夹路径
  5. Processing files in the folder:
    Use the glob() function to get the list of files in the specified folder, and process each file in turn through a loop. The following code will show how to traverse all files in a folder:

    $files = glob($directory . '/*'); // 获取文件列表
    
    foreach($files as $file) {
     // 在这里处理每个文件
    }
  6. Write file processing logic:
    Write the logic for processing files according to specific needs. The following are some common file processing operations:
  7. Get the file name and extension: Use the basename() and pathinfo() functions to get the file name and extension :

    $filename = basename($file); // 获取文件名
    $extension = pathinfo($filename, PATHINFO_EXTENSION); // 获取扩展名
  • Read file contents: Use file_get_contents() function to read file contents:

    $content = file_get_contents($file); // 读取文件内容
  • Write file contents: use file_put_contents()Function to write contents to file:

    $new_content = 'Hello World!';
    file_put_contents($file, $new_content); // 将内容写入文件
  • Delete file: useunlink()Function to delete files:

    unlink($file); // 删除文件

Comprehensive example:
The following is a comprehensive example that will demonstrate how to batch process the text content in the file and replace the specified words with the specified String:

<?php
$directory = '/var/www/html/files'; // 文件夹路径
$search_word = 'apple'; // 要替换的单词
$replace_word = 'orange'; // 替换为的字符串

$files = glob($directory . '/*'); // 获取文件列表

foreach($files as $file) {
    $content = file_get_contents($file); // 读取文件内容
    $new_content = str_replace($search_word, $replace_word, $content); // 替换字符串
    file_put_contents($file, $new_content); // 将替换后的内容写入文件
}
?>

Summary:
Batch processing files in Linux through PHP scripts can help us complete various file operation tasks efficiently. This article describes how to set the folder path, traverse the files in the folder, and specific file processing operations, and provides code examples. Using these methods and examples, you can perform corresponding file processing operations according to your own needs.

The above is the detailed content of How to batch process files in Linux via PHP script. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1510
276
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

How to Schedule Tasks on Linux with Cron and anacron How to Schedule Tasks on Linux with Cron and anacron Aug 01, 2025 am 06:11 AM

cronisusedforpreciseschedulingonalways-onsystems,whileanacronensuresperiodictasksrunonsystemsthataren'tcontinuouslypowered,suchaslaptops;1.Usecronforexacttiming(e.g.,3AMdaily)viacrontab-ewithsyntaxMINHOURDOMMONDOWCOMMAND;2.Useanacronfordaily,weekly,o

edge pdf viewer not working edge pdf viewer not working Aug 07, 2025 pm 04:36 PM

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

Java Performance Optimization and Profiling Techniques Java Performance Optimization and Profiling Techniques Jul 31, 2025 am 03:58 AM

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

Using PHP for Data Scraping and Web Automation Using PHP for Data Scraping and Web Automation Aug 01, 2025 am 07:45 AM

UseGuzzleforrobustHTTPrequestswithheadersandtimeouts.2.ParseHTMLefficientlywithSymfonyDomCrawlerusingCSSselectors.3.HandleJavaScript-heavysitesbyintegratingPuppeteerviaPHPexec()torenderpages.4.Respectrobots.txt,adddelays,rotateuseragents,anduseproxie

How to install software on Linux using the terminal? How to install software on Linux using the terminal? Aug 02, 2025 pm 12:58 PM

There are three main ways to install software on Linux: 1. Use a package manager, such as apt, dnf or pacman, and then execute the install command after updating the source, such as sudoaptininstallcurl; 2. For .deb or .rpm files, use dpkg or rpm commands to install, and repair dependencies when needed; 3. Use snap or flatpak to install applications across platforms, such as sudosnapinstall software name, which is suitable for users who are pursuing version updates. It is recommended to use the system's own package manager for better compatibility and performance.

Yii Developer: Mastering the Essential Technical Skills Yii Developer: Mastering the Essential Technical Skills Aug 04, 2025 pm 04:54 PM

To become a master of Yii, you need to master the following skills: 1) Understand Yii's MVC architecture, 2) Proficient in using ActiveRecordORM, 3) Effectively utilize Gii code generation tools, 4) Master Yii's verification rules, 5) Optimize database query performance, 6) Continuously pay attention to Yii ecosystem and community resources. Through the learning and practice of these skills, the development capabilities under the Yii framework can be comprehensively improved.

See all articles