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']);
本文来自博客园,作者:Carvers,转载请注明原文链接:https://www.cnblogs.com/carver/articles/18850046

浙公网安备 33010602011771号