Hongmu Notes
Home Language Notes Batch add header configuration to PHP files
Language Notes PHP

Batch add header configuration to PHP files

Batch add header configuration to PHP files

20251209140903622-image

User-friendly and loved by users!

<?php
// 安全提示:建议在测试环境中先运行,备份重要文件
echo "<h3>PHP文件批量添加头部配置</h3>";

// 检查是否有确认参数
if (isset($_GET['confirm']) && $_GET['confirm'] == 'yes') {
    addConfigToPhpFiles();
} else {
    showWarning();
}

function showWarning() {
    echo "<div style='background-color:#fff3cd; border:1px solid #ffeaa7; padding:15px; margin:20px; border-radius:5px;'>";
    echo "<h4>⚠️ 安全警告</h4>";
    echo "<p>此脚本将执行以下操作:</p>";
    echo "<ol>";
    echo "<li>递归扫描当前目录及其所有子目录</li>";
    echo "<li>查找所有 .php 文件</li>";
    echo "<li>在每个PHP文件的开头添加 <code>&lt;?php require_once '../admin/config.php';?&gt;</code></li>";
    echo "</ol>";
    echo "<p style='color:#d63031; font-weight:bold;'>注意:此操作不可逆,请确保已备份重要文件!</p>";
    echo "<br>";
    echo "<a href='?confirm=yes' style='background-color:#e74c3c; color:white; padding:10px 20px; text-decoration:none; border-radius:4px;'>确认执行添加配置</a>";
    echo "&nbsp;&nbsp;";
    echo "<a href='?' style='background-color:#95a5a6; color:white; padding:10px 20px; text-decoration:none; border-radius:4px;'>取消</a>";
    echo "</div>";
}

function addConfigToPhpFiles() {
    $baseDir = __DIR__; // 当前目录(根目录)
    $configCode = "<?php require_once '../admin/config.php';?>\n";
    $count = 0;
    $errors = 0;
    $skipped = 0;
    
    echo "<div style='background-color:#d4edda; border:1px solid #c3e6cb; padding:15px; margin:20px; border-radius:5px;'>";
    echo "<h4>正在执行添加配置操作...</h4>";
    echo "<p>要添加的配置代码: <code>" . htmlspecialchars($configCode) . "</code></p>";
    
    // 使用递归迭代器遍历所有目录
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($baseDir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $file) {
        // 检查是否是.php文件
        if ($file->isFile() && strtolower($file->getExtension()) === 'php') {
            $filePath = $file->getPathname();
            $fileName = $file->getFilename();
            
            // 跳过当前脚本自身
            if ($fileName === basename(__FILE__)) {
                continue;
            }
            
            // 跳过admin目录下的config.php文件
            if (strpos($filePath, '/admin/config.php') !== false || 
                strpos($filePath, '\\admin\\config.php') !== false) {
                continue;
            }
            
            echo "<p>处理文件: " . htmlspecialchars($filePath) . "</p>";
            
            // 读取文件内容
            $content = file_get_contents($filePath);
            if ($content === false) {
                echo "<p style='color:#c0392b;'>错误: 无法读取文件 " . htmlspecialchars($filePath) . "</p>";
                $errors++;
                continue;
            }
            
            // 检查是否已经包含配置代码
            if (strpos($content, "require_once '/admin/config.php';") !== false) {
                echo "<p style='color:#f39c12;'>跳过: 文件已包含配置代码</p>";
                $skipped++;
                continue;
            }
            
            // 检查文件是否已经有PHP开放标签
            $hasOpeningTag = (strpos($content, '<?php') !== false);
            
            // 准备新内容
            $newContent = $configCode . $content;
            
            // 如果文件没有PHP开放标签但我们的配置代码添加了,这没问题
            // 如果文件已经有PHP开放标签,我们只需要在开头添加配置代码
            
            // 写入文件
            if (file_put_contents($filePath, $newContent) !== false) {
                echo "<p style='color:#27ae60;'>成功: 已添加配置代码</p>";
                $count++;
            } else {
                echo "<p style='color:#c0392b;'>错误: 无法写入文件 " . htmlspecialchars($filePath) . "</p>";
                $errors++;
            }
        }
    }
    
    echo "<hr>";
    echo "<h4>操作完成!</h4>";
    echo "<p>成功添加配置: <strong>{$count}</strong> 个文件</p>";
    echo "<p>跳过已包含配置: <strong>{$skipped}</strong> 个文件</p>";
    echo "<p>遇到错误: <strong>{$errors}</strong> 个文件</p>";
    echo "<p><a href='?'>返回</a></p>";
    echo "</div>";
}

// 显示当前目录信息
echo "<div style='background-color:#e9ecef; padding:10px; margin:10px 0; border-radius:4px;'>";
echo "<p><strong>当前目录:</strong> " . htmlspecialchars(__DIR__) . "</p>";
echo "<p><strong>配置路径:</strong> /admin/config.php</p>";
echo "</div>";
?>

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Bilingual (Chinese/English) Outdoor Tent and Sleeping Bag Website Template – 1074

Bilingual (Chinese/English) Outdoor Tent and Sleeping Bag Website Template – 1074 Practical Collection Yiyou template

This bilingual (Chinese/English) EyouCMS template is ideal for businesses specializing in outdoor tent camps, tents, and sleeping bags. Its international outdoor design style effectively showcases outdoor gear products, tents, sleeping bags, and the company's competitive advantages in the export market. It helps outdoor equipment exporters promote their brands across global markets. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 61
(Adaptive mobile version) Hotel & Homestay Website PBootCMS Template – Download Hotel & Guest Room Website Source Code – 0491

(Adaptive mobile version) Hotel & Homestay Website PBootCMS Template – Download Hotel & Guest Room Website Source Code – 0491 Practical Collection pbootcms Template

A PbootCMS website template designed for the hotel, guesthouse, and guest room hospitality industry, compatible with both PC and WAP devices. Its warm and cozy design effectively showcases the hotel's environment, room types and facilities, as well as online booking services. This template helps guesthouses or hotels attract online visitors and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5...
👁 53
Responsive Yoga Training & Yoga Equipment Website Template – 0471

Responsive Yoga Training & Yoga Equipment Website Template – 0471 Practical Collection Yiyou template

An eyouCMS responsive website template designed for the yoga training and yoga equipment industry. Its healthy and comfortable design is ideal for showcasing yoga classes, training programs, yoga products, instructor teams, and teaching environments. This template helps yoga brands attract online participants and enhance their brand awareness. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Questions About Installing EasyYou CMS...
👁 26
(Adaptive mobile version) Website building company website template Internet company website source code download 1060

(Adaptive mobile version) Website building company website template Internet company website source code download 1060 Practical Collection pbootcms Template

A PbootCMS website template for website building companies and Internet companies, supporting PC and WAP. The design style is modern and technological, suitable for website construction companies and IT service providers to display cases and services. It helps Internet companies attract corporate customers who need to build websites online. Template display Installation instructions Website backend:/admin.php Account: admin Password: admin Unzip password: www.4s5.cn Related articles…
👁 35
Responsive bilingual (Chinese/English) building materials exhibition and sales website template – 1075

Responsive bilingual (Chinese/English) building materials exhibition and sales website template – 1075 Practical Collection Yiyou template

An eYouCMS responsive website template designed specifically for the bilingual (Chinese and English) building materials exhibition and sales industry. Its international, professional design style enables effective presentation of building materials products, export advantages, project cases, and brand image. The multi-language support facilitates brand promotion for building materials enterprises in global markets. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS...
👁 44
(Adaptive Mobile Version) HTML5 Smart Device PBootCMS Website Template – Responsive AI-powered Website Source Code Download – 0492

(Adaptive Mobile Version) HTML5 Smart Device PBootCMS Website Template – Responsive AI-powered Website Source Code Download – 0492 Practical Collection pbootcms Template

A PbootCMS responsive website template designed for smart devices and AI-powered robots, compatible with both PC and WAP devices. Its futuristic design is ideal for showcasing AI products, smart hardware, and technical solutions, helping smart technology companies establish a cutting-edge online brand presence. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s...
👁 48