Loading

php 通过加密路径访问资源

本文章以通过加密路径访问对应真实路径的图片:
Laravel框架代码案例:

try {
    $file_data = Files::query()
        ->where('md5_path', $md5)
        ->whereNotNull('path')
        ->select('path', 'mime', 'size')
        ->first();
    if (!$file_data) {
        throw new \Exception(trans('messages.not_find_this_file_params_error'), CodeStatus::PARAMS_ERROR_CODE);
    }
    // 輸出圖片
    $file_full_path = Storage::disk('safe')->path($file_data->path);
    if (file_exists($file_full_path)) {
        $headers = [
            'Content-type'        => $file_data->mime,
            'Content-Disposition' => 'inline; filename="' . basename($file_data->name) . '"',
            'Content-Length'      => $file_data->size,
        ];
        return response()->stream(function () use ($file_full_path) {
            $fileHandle = fopen($file_full_path, 'rb'); // Open the file in binary read mode
            while (!feof($fileHandle)) {
                $chunk = fread($fileHandle, 8192); // Read a chunk of data (adjust the chunk size as needed)
                echo $chunk; // Output the chunk to the response
            }
            fclose($fileHandle); // Close the file handle
        }, 200, $headers);
    } else {
        // 文件不存在,返回适当的错误响应
        throw new \Exception(trans('messages.not_find_this_file_params_error'), CodeStatus::PARAMS_ERROR_CODE);
    }
} catch (\Exception $e) {
    return response()->json(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
}

访问路由:

//获取文件
Route::get('/images/{md5}', [\App\Http\Controllers\Admin\CommonAdminController::class, 'getImage']);
posted @ 2025-04-27 17:57  Carvers  阅读(18)  评论(0)    收藏  举报