How to upload a file

How to upload a file is a simple steps article about how can we upload a file in Yii2 easily.

I hope this will be of some help :slight_smile:

Thanks for sharing such a great method

Looks better and cool :rolleyes:

I customize your lookup code in my project.Thanks.

You should show your code and instructions here on the forum, instead of just linking to your site. That way it is available when your site is down, and you aren’t just advertising/spamming your website here. I don’t think the link to your site is an issue (at least with a substantive post), but just linking to your forum saying “go here for this”, “go here for that”, is frowned upon on most forums.

You should remove the var_dump() from line 27 on step 2.

UploadedFile::getInstance() is NULL when no file is uploaded, so your code should return null as well instead of false.

I think getUploadedFile() is not necessary. The default avatar should be handled in the view, so it can be changed easier later. Following MVC principles, assigning the default image belongs in the view.

To make things more precise, and possibly reduce future errors, I would use the ‘@web’ alias in the fileUploadUrl param.

I personally think your uploadFile() should actually finish the job and save the file within the function.

The max length for ‘name’ and ‘pic’ probably doesn’t need to allow 255 chars. In your table, you should limit chars and not blindly use 255 for things that will always be much shorter. On a large active site, tons of ‘varchar’ columns all max of 255 will suffer performance issues.

There is no error handling if the file fails to upload.

I would use something other than the timestamp for the file name. I have seen in vulnerable scripts, where they were able to get a php script uploaded (faking as an image) and they knew the timestamp, so was able to easily find their backdoor (shell) that they uploaded.I would use generateRandomString() in the Security class. It has a max length of 32, so you could trim your db column to varchar(32) and maxlength in your model.

Will this allow jpeg? Both jpg and jpeg are perfectly valid extensions. I haven’t checked if the yii built in file extension can handle the difference or if we have to explicitly define ‘jpg’ and ‘jpeg’,

I do want to give the 2 main positives with your example. You restrict to the image extensions AND you restrict by mimetype.

In all, good job and it should be pretty secure. A little refactoring, but it will get the job done ;)

Note to the public: When you upload files, you MUST restrict by the file extension at the very least! DO NOT EVER split the filename and grab what is after the dot! It is not safe and can be manipulated, use pathinfo() to get the extension. Yii does this for you if you look at UploadedFile::getExtension(). By restricting by mimetype, you are adding even more security! See this mimetype list for help.