Answer the question
In order to leave comments, you need to log in
How to safely upload an image to the server?
Interested in the question of how to safely upload an image to the server?
There is the following code:
<div class="file-upload" id="file-upload">
<label>
<input type="file" id="avatarchange" name="file">
<span>Выберите файл</span>
</label>
</div>
$('#avatarchange').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$('.file-upload span').text('Фото загружено');
setTimeout(avatarOk, 3000);
$(".img").attr('style','background: url('+URL.createObjectURL(event.target.files[0])+') no-repeat center center / cover;');
});
Answer the question
In order to leave comments, you need to log in
On the PHP side, pass the resulting file through the GD library.
If necessary, reduce the quality of the output file, and along the way generate a preview by sending it back to the client (+ confirming receipt by the server).
Note that you will have to increase the available RAM for one PHP process.
In my experience, for GD to swallow a 16 megapixel picture, you need 128 MB of RAM.
Before we feed GD, we weight the image using getimagesize().
If this is not done, and if the limit is exceeded, given to the library for processing, then the script will quietly die out without telling the client anything, otherwise you can generate a message that the file is large.
Of course, you need to check both the mime type, and check the validity of images at least with the getimagesize() function, and do resize(). All this can be googled if you wish.
What is usually not written is about the load on the server when processing the image.
I recommend loading pictures as is (limiting only by file size), and if the pictures are not loaded at the same time, then you can also hang a lock. Further, process them as a separate process asynchronously (by cron, for example, or by some kind of queue manager).
1) Don't trust anything that arrives in $_FILES;
2) Check mime against whitelists via finfo (here and file size);
3) Check extension from $_FILES against whitelists, match against mime;
4) Form the file name and extension yourself;
5) Forbid the web server to execute php in the folder where the upload is stored;
5.1) Ideally, upload everything to a separate server (or a subdomain under a different user) purely for static, where php is generally disabled.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question