Laravel getimagesize 因完整 URL 而崩溃

标签 laravel

如果我这样做:

$image = '/storage/images/image.jpg';
list($width, $height) = getimagesize($image);

我得到:getimagesize(/storage/images/image.jpg): failed to open stream: No such file or directory这是有道理的,因为它没有完整的 URL。

但是如果我这样做:

$image = url('/').'/storage/images/image.jpg'; // Added url('/')
list($width, $height) = getimagesize($image);

页面永远卡在loading状态...

一些额外的信息

  • public、storage、images文件夹都有755权限
  • 图片本身有644张,显示在前端
  • 我正在使用 Spatie Media Library ,而我试图从中获取尺寸的图像来自转换。但是由于它们在前端显示得非常好,我不明白为什么这会导致脚本使服务器崩溃
  • 这是在本地主机上

更新

看起来服务器崩溃了,我以为不会有错误日志,但是有:

getimagesize(http://127.0.0.1:8000/storage/images/image.jpg): failed to open stream: HTTP request failed!  {"exception":"[object] (ErrorException(code: 0): getimagesize(http://127.0.0.1:8000/storage/images/image.jpg): failed to open stream: HTTP request failed!  at /Users/username/Documents/dev/test/app/Http/Controllers/PagesController.php:50)

PagesController 中的第 50 行是

list($width, $height) = getimagesize($image);

并如指示$image = url('/').'/storage/images/image.jpg';

如果我输入 URL http://127.0.0.1:8000/storage/images/image.jpg在浏览器中它显示图像。

更新 2

file_get_contents($image)给出相同的行为,所以它可能与 Laravel 的路由或脚本请求与浏览器请求不同这一事实有关?

更新 3

在 config/filesystems.php 中

'images' => [
            'driver' => 'local',
            'root' => storage_path('app/public/images'),
            'url' => env('APP_URL').'/storage/images',
            'visibility' => 'public',
        ],

public 中有一个符号链接(symbolic link)php artisan storage:link 创建的文件夹

最佳答案

您正在尝试访问 /storage/images/image.jpg。你的真实路径是这样的:/var/www/laravel.app/storage/app/public/images/image.jpg

您应该使用 Storage facade 及其 path() 方法来检索完整的绝对路径:

$image = Storage::path('public/images/image.jpg');
list($width, $height) = getimagesize($image);

storage_path() 助手:

$image = storage_path('app/public/images/image.jpg');

关于Laravel getimagesize 因完整 URL 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896079/

相关文章:

php - 如何对具有配置设置的对象进行建模

php - Laravel Eloquent 无法确定表

Laravel Nova - 重新加载资源的索引 View

mysql - 将 Controller 在 Blade 文件中获取的值传递给查询

php - Laravel Eloquent 查询从另一个模型获取用户

mysql - 每月计算结果并聚合的 Laravel 原始查询

Laravel 辅助数据库连接不起作用

PHP/Laravel - 有条件地显示 Blade View

function - laravel - 为什么函数调用没有括号?

laravel - 使用 Amazon S3 的 Storage::get() 返回 false