theprogrammer theprogrammer - 5 months ago 9
PHP Question

php stops working if user uploads exe

i don't know if something's wrong with my php script however i am doing upload system whenever the user uploads file type other than jpg/jpeg/gif (any image extension) the script breaks. php won't load until i restart phpstorm and my code is really small. i don't want user to upload exe or other file extension. but the script breaks which ruins the UX. my code is really small but i will share it

if(!$_FILES['file']['tmp_name'])
{
$uploaderrors[] = "Please choose image";
}
$check = getimagesize($_FILES['file']['tmp_name']);
if($check == false)
{
$uploaderrors[] = "Please choose image";
}
}




is there anyway i can fix this?

Answer

Simply use Javascript (perhaps JQuery) to check that the User uploads the correct File Format before your PHP kicks in... that would be one way of doing it on the Client-Side. Here is an example:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <script type="text/javascript">
            (function($) {
                $(document).ready(function(){
                    // ASSUMING THAT YOUR FILE INPUT HAS A CLASS-NAME OF "file_upload"
                    // WE CAN SIMPLY GRAB IT INTO A VARIABLE LIKE SO:
                    var pixFile = $(".file_upload");

                    // NOW, WHEN THE USER INTERACTS WITH THIS FILE-INPUT
                    // WE CAN REACT TO THE CHANGE EVENT...
                    pixFile.on("change", function(evt){
                        var dis_val     = $(this).val();

                        // IF USER TRIES TO UPLOAD ANYTHING OUTSIDE ACCEPTABLE/VALID IMAGE FORMATS
                        // WE INFORM HIM OF OUR PREFERENCES: HERE WE ARE USING ALERT...
                        if( !/(\.)(jpg|jpeg|png|gif|bmp)$/.test(dis_val) ){         // ADD OTHER FORMATS YOU WISH TO SUPPORT:  'tiff, psd, pdf'
                            alert("You can only upload image Files (JPG, JPEG, PNG, GIF, BMP)");    // ADD OTHER FORMATS YOU WISH TO SUPPORT

                            // THEN IMMEDIATELY RESET THE VALUE OF THE UPLOADED FILE TO NULL
                            $(this).val(null);
                            return false;
                        }else{
                            // OTHERWISE: WE KNOW THAT USER UPLOADED THE ACCEPTABLE FILE FORMAT(S)
                            // YOU MAY OR MAY NOT WANT TO REACT TO THIS... THE CHOICE IS YOURS
                            // AND YOU MAY AS WELL JUST DELETE THE ENTIRE ELSE CLAUSE (IF YOU SO WISH)
                        }
                    });
                });
            })(jQuery);
        </script>