You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP图片批量处理脚本部署InfinityFree服务器报错求助

PHP图片批量处理脚本服务器部署错误修复方案

错误原因分析

从报错信息可以明确核心问题:服务器无法识别并访问你输入的Windows本地路径:

  • 服务器是Linux系统,不支持C:\Users\abc\Desktop\ex这类Windows格式路径
  • 服务器没有权限,也不可能访问到你本地电脑的文件夹
  • 后续的解压、目录遍历等操作都因路径不存在而失败

修复方案

1. 替换本地路径输入为文件上传功能

服务器环境下,必须让用户直接上传需要处理的Zip文件,而非输入本地路径。将原表单修改为文件上传表单。

2. 调整文件操作到服务器可写目录

所有临时文件、处理后的文件都放在服务器权限范围内的目录,比如网站根目录下的uploads、temp、output子目录,或使用服务器临时目录。

3. 修复权限与路径兼容问题

  • Linux系统使用/作为路径分隔符,避免使用Windows的\
  • 创建目录时使用服务器允许的权限(如0755),防止权限错误

修改后的完整代码

<h2>Bulk upload Image Renamer</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
    <label for="zipFile">Upload Zip File:</label>
    <input type="file" id="zipFile" name="zipFile" accept=".zip" required>
    <button type="submit">Process Images</button>
    <button type="reset">Reset</button>
</form>

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 初始化服务器端目录
$uploadDir = __DIR__ . '/uploads/';
$tempDir = __DIR__ . '/temp/';
$outputDir = __DIR__ . '/output/';

// 创建必要目录
foreach ([$uploadDir, $tempDir, $outputDir] as $dir) {
    if (!file_exists($dir)) {
        mkdir($dir, 0755, true);
    }
}

// 解压上传的Zip文件到临时目录
function unzipUploadedFile($zipPath, $extractDir) {
    $zip = new ZipArchive;
    if ($zip->open($zipPath) === true) {
        $zip->extractTo($extractDir);
        $zip->close();
        return true;
    }
    return false;
}

// 删除二级子文件夹,将内容移到父文件夹
function flattenSubfolders($folderPath) {
    $subfolders = glob($folderPath . '/*', GLOB_ONLYDIR);
    foreach ($subfolders as $subfolder) {
        $secondLevel = glob($subfolder . '/*', GLOB_ONLYDIR);
        if (!empty($secondLevel)) {
            foreach ($secondLevel as $level2) {
                $files = glob($level2 . '/*');
                foreach ($files as $file) {
                    rename($file, $subfolder . '/' . basename($file));
                }
                removeDirectory($level2);
            }
        }
    }
}

// 重命名子文件夹中的图片
function renameImages($folderPath) {
    $subfolders = glob($folderPath . '/*', GLOB_ONLYDIR);
    if (empty($subfolders)) {
        echo "<p>No subfolders found in processed directory</p>";
        return;
    }

    echo "<ul>";
    foreach ($subfolders as $subfolder) {
        $subfolderName = basename($subfolder);
        echo "<li>$subfolderName - ";

        $images = glob($subfolder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
        if (empty($images)) {
            echo "No images found";
        } else {
            foreach ($images as $image) {
                $imageName = basename($image);
                $newName = $subfolderName . '_' . $imageName;
                $newPath = $subfolder . '/' . $newName;
                if (rename($image, $newPath)) {
                    echo "$newName, ";
                } else {
                    echo "Failed to rename $imageName, ";
                }
            }
        }
        echo "</li>";
    }
    echo "</ul>";
}

// 收集所有图片并生成Zip文件
function createOutputZip($sourceDir, $outputPath) {
    $zip = new ZipArchive();
    if ($zip->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($sourceDir),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($iterator as $file) {
            if (!$file->isDir()) {
                $ext = strtolower(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                    $zip->addFile($file->getRealPath(), basename($file->getRealPath()));
                }
            }
        }
        $zip->close();
        return true;
    }
    return false;
}

// 删除目录及内容
function removeDirectory($dir) {
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        is_dir($path) ? removeDirectory($path) : unlink($path);
    }
    return rmdir($dir);
}

// 主处理流程
function processUploadedZip($zipFile) {
    global $uploadDir, $tempDir, $outputDir;

    // 保存上传的Zip文件
    $uploadedPath = $uploadDir . basename($zipFile['name']);
    if (!move_uploaded_file($zipFile['tmp_name'], $uploadedPath)) {
        echo "<p>Failed to upload zip file</p>";
        return;
    }

    // 解压到临时目录
    $extractPath = $tempDir . uniqid('extract_');
    mkdir($extractPath, 0755);
    if (!unzipUploadedFile($uploadedPath, $extractPath)) {
        echo "<p>Failed to extract zip file</p>";
        removeDirectory($extractPath);
        unlink($uploadedPath);
        return;
    }

    // 处理文件夹结构
    flattenSubfolders($extractPath);
    // 重命名图片
    renameImages($extractPath);
    // 生成输出Zip
    $outputZip = $outputDir . 'bulk_upload_images_' . date('YmdHis') . '.zip';
    if (createOutputZip($extractPath, $outputZip)) {
        echo "<p>Zip file created successfully</p>";
        echo "<a href='" . str_replace(__DIR__, '', $outputZip) . "'>Download Processed Zip</a>";
    } else {
        echo "<p>Failed to create output zip file</p>";
    }

    // 清理临时文件
    removeDirectory($extractPath);
    unlink($uploadedPath);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['zipFile'])) {
    processUploadedZip($_FILES['zipFile']);
}
?>

使用说明

  1. 上传包含子文件夹的Zip文件,子文件夹中存放目标图片
  2. 脚本自动完成解压、扁平化文件夹结构、按父文件夹名称重命名图片操作
  3. 最终生成包含所有重命名图片的Zip文件,可直接下载

内容的提问来源于stack exchange,提问作者Saurabh Giri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:45:55