1702730864

Secure file upload using php


![uploadFile](https://i.pinimg.com/originals/ea/b6/cf/eab6cf28102b5af5afd6b0ed21fbf787.gif) A major service offered by many web sites is the facility for users to upload files and images. For example, you may wish to let your users create avatars or upload photos they have taken. Or perhaps you need to support the uploading of Word, Excel, or other types of files. Using this recipe, you can enable this feature while retaining the security of your web site. ## About the Recipe This recipe takes the name of a form field used to upload a file to a web server and returns the uploaded file in a string. Upon success, it returns a two-element array, the first value of which is zero and the second is the uploaded file. html ``` <form method="post" action="$_SERVER[PHP_SELF]" enctype="multipart/form-data"> <input type="hidden" name="flag" value="1"> <input type="file" name="test"> <input type="submit" value="Upload"> </form> ``` php ```php if(isset($_POST["flag"])){ $result = UploadFile("test", array("image/jpeg", image/pjpeg), 100000); if($result[0] == 0){ file_put_contents("test.jpg", $result[2]); echo "File received with the type $result[1] and saved"; }else { if($result[0] == -2) echo "wrong file type"; if($result[0] == -3) echo "Maximum length exceeded"; if($result[0] > 0) echo "Error code: $result"; echo "File upload failed"; } } function UploadFile($name, $typefile, $maxlen) { if(!isset($_FILES[$name]["name"])) return array(-1, NULL, NULL); if(!in_array($_FILES[$name]["type"], $filetype)) return array(-2, NULL, NULL); if($_FILES[$name]["size"] > $maxlen) return array(-3, NULL, NULL); if($_FILES[$name][error] > 0) return array($_FILES[$name], NULL, NULL); $temp = file_get_contents($_FILES[$name][ mp_name]); return array(0, $_FILES[$name], $temp); } ``` if you are more interested in talking about this code you can call me in this chatroom here [https://chat-to.dev/chat?q=phpBeginners](https://chat-to.dev/chat?q=phpBeginners) leave a comment here if this code was useful to you. if you do, you ll be helping my work. thanks

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2024 © Chat-to.dev]