Search code examples
phpyii2getimagesize

getimagesize() not working properly in Yii2


Cannot get this function to work inside my controller. It always return

getimagesize(/web/uploads/image1.jpg): failed to open stream: No such file or directory

calling it like this:

$user->avatar = Yii::$app->getUrlManager()->getBaseUrl() . '/uploads/' . $model->avatar->baseName . '.' . $model->avatar->extension;   
getimagesize($user->avatar );  

Any solutions?

Accessing /web/uploads/image1.jpg from browser image is shown.


Solution

  • getimagesize is native PHP function and has nothing to do with framework. You need to specify full image path using basePath, not baseUrl. baseUrl is for displaying images.

    Construct your path like this instead:

    use Yii;
    
    ...
    
    $imagePath = Yii::$app->basePath . '/web/uploads/' . $model->avatar->baseName . '.' . $model->avatar->extension;
    

    You can also set the alias for uploads folder like this in bootstrap.php file (this example is for advanced app):

    Yii::setAlias('uploads', dirname(dirname(__DIR__)) . '/frontend/web/uploads');
    

    Then to get full path to uploads folder you can refer to it like this:

    Yii::getAlias('uploads');