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

如何在Laravel NativePHP应用中启用php-zip解决ZipArchive缺失问题

问题:Laravel NativePHP应用启用php-zip扩展修复ZipArchive类找不到错误

我正在使用Laravel NativePHP包开发桌面应用,应用运行正常,但尝试使用ZipArchive类生成压缩文件时,出现错误:Class "ZipArchive" not found。

以下是控制器代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Response;
use Illuminate\Support\Facades\File;
use ZipArchive;

class Home extends Controller
{
    /**
     * Show form
     *
     */
    public function index()
    {
        return view('generate-zip');
    }

    public function generateZip(Request $request)
    {
        try {
            $file = $request->file('fileInput');
            $fileContents = file($file->getPathname());
            $folderPath = $request->textInput;

            $destination = public_path($folderPath.'/selected-images.zip');
            $zip = new ZipArchive();
            $zip->open($destination, ZipArchive::CREATE);

            foreach ($fileContents as $line) {
                $data = str_getcsv($line);
                $imgName = $data[0];
                if ($imgName) {
                    $localFilePath = $folderPath.'/'.$imgName;
                    $file = public_path($localFilePath);

                    if (File::exists($file)) {
                        $zip->addFile($file, $imgName);
                    }
                }

            }
            $zip->close();

        } catch (\Exception $e) {
            return redirect()->back()->withError([$e->getMessage()]);
        }
    }
}

这段代码在网页浏览器中运行正常,但在NativePHP应用中报错。通过phpinfo()检查发现,网页端已启用Zip扩展,但NativePHP应用中未启用,且两者使用的PHP版本不同:NativePHP为8.2.8,网页端为8.2.14。


解决方案

NativePHP使用独立的PHP运行环境,需针对该环境启用zip扩展,步骤如下:

  1. 定位NativePHP的PHP目录
    NativePHP自带的PHP环境默认存放在项目的vendor/nativephp/php-bin目录下,根据你的操作系统,进入对应子目录(比如windows、macos或linux)。

  2. 修改PHP配置文件php.ini

    • 找到目录中的php.ini文件(若只有php.ini-development或php.ini-production,复制一份并重命名为php.ini)。
    • 查找;extension=zip这一行,去掉开头的分号;,启用该扩展;如果没有这行,手动添加:
      • Windows系统:extension=php_zip.dll
      • macOS/Linux系统:extension=zip.so(PHP 8+版本直接写extension=zip即可)
  3. 验证扩展状态
    在NativePHP应用中重新输出phpinfo(),确认Zip扩展已显示为启用状态。

  4. 重新运行应用
    重启NativePHP应用,测试ZipArchive功能是否正常。若仍不生效,执行php artisan native:build重新构建应用,清除缓存。

补充说明:

  • macOS/Linux用户若遇到扩展无法加载,需确保系统已安装libzip依赖:
    • macOS:brew install libzip
    • Ubuntu/Debian:sudo apt-get install libzip-dev

内容的提问来源于stack exchange,提问作者Mukesh Khatri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:46:33