Geoff
Geoff

Reputation: 6639

Getting an extension of an uploaded file in yii2

I'm trying to get an extension of a file during upload but I get an error that path info requires a string:

I have tried:

$path_parts = pathinfo($_FILES['evidence']['name']);
echo $path_parts['extension'];

How can extract file extension, for example jpeg, doc, pdf, etc.

Upvotes: 2

Views: 8941

Answers (2)

Touqeer Shafi
Touqeer Shafi

Reputation: 5264

If you are using yii2 kartik file input you can get the instance of yii\web\uploadedFile this way to:

$file = UploadedFile::getInstanceByName('evidence'); // Get File Object byName
 // Then you can get extension by this:
$file->getExtension()

If you want to validate file as well then you can use FileValidator using adhoc role:

$validator = new FileValidator(['extensions' => ['png','jpg']]);
if( $validator->validate($file, $errors) ) {
    // Validation success now you can save file using $file->saveAs method
} else {
    // ToDO with error: print_r($errors);   
}

Upvotes: 5

arogachev
arogachev

Reputation: 33548

It's better not use $_FILES directly in Yii2 since framework provides abstraction with a class yii\web\UploadedFile. There is also separate page in guide describing working with uploaded files.

There is an example with model.

namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $imageFile;

    public function rules()
    {
        return [
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    public function upload()
    {
        if ($this->validate()) {
            $this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
            return true;
        } else {
            return false;
        }
    }
}

As you can see, extension is extracted using extension property ($this->imageFile->extension).

There are more info about form settings, handling in controller, uploading multiple files. All this can be found by the link mentioned above.

Upvotes: 2

Related Questions