File Upload Class


/ Published in: PHP
Save to your folder(s)

You may wanna mess with it to suit your needs (like setting the folder to 0777).


Copy this code and paste it in your HTML
  1. class uploadFile
  2. {
  3. public $target;
  4. public $finalFileName;
  5. public $elementId;
  6. public $checkSize;
  7. public $allowOverwrite;
  8. public $emptyFolder;
  9. public $createFolder;
  10.  
  11. function upload()
  12. {
  13. if(!isset($this->finalFileName)) { $this->finalFileName = basename($_FILES[$this->elementId]['name']); }
  14. if(!isset($this->allowOverwrite)) { $this->allowOverwrite = false; }
  15. if(!isset($this->emptyFolder)) { $this->emptyFolder = false; }
  16. if(!isset($this->createFolder)) { $this->createFolder = true; }
  17.  
  18. $type = $_FILES[$this->elementId]['type'];
  19. $fileTarget = $this->target . $this->finalFileName;
  20. $ext = substr($this->finalFileName, -3);
  21.  
  22. $fileBeginning = str_replace('.','',$this->finalFileName);
  23.  
  24. if($this->checkSize)
  25. {
  26. if(isImage($type))
  27. {
  28. $size = getimagesize($_FILES[$this->elementId]['tmp_name']);
  29. if($size[0] > 500 || $size[1] > 500)
  30. {
  31. return false;
  32. }
  33. }
  34. }
  35.  
  36. if(!checkForInvalidChars($fileBeginning))
  37. {
  38. return false;
  39. }
  40. if($this->emptyFolder)
  41. {
  42. $getFile = new getFileNameFromFolder();
  43. $getFile->folderName = $this->target;
  44. $filename = $getFile->returnFileName();
  45. }
  46. if(!file_exists($this->target)&&$this->createFolder)
  47. {
  48. mkdir($this->target,0777,true);
  49. }
  50.  
  51. if(file_exists($fileTarget)&&!$this->allowOverwrite) { return false; }
  52.  
  53. if(move_uploaded_file($_FILES[$this->elementId]['tmp_name'], $fileTarget))
  54. {
  55. if($this->emptyFolder&&$filename!="File/Folder doesn't exist.") { unlink($this->target.$filename); } //only unlink if file upload was successful and there is a previous file in the folder.
  56. return true;
  57. }
  58. else
  59. {
  60. return false;
  61. }
  62. }
  63. }
  64. /*
  65. properties:
  66. elementId - the name of the element submitting the file
  67. finalFileName - defaults to the file name, change it if you want to store it with a diff. name
  68. target - the location you wanna store the file in
  69. checkSize - will do a check against the image type/size you may wanna modify that to suit your needs
  70. allowOverwrite - defaults to false, true = overwrite file if it exists, false = don't
  71. emptyFolder - defaults to false, true = empty target folder contents before uploading
  72. createFolder - defaults to true, true = create folder if it doesn't exist.
  73.  
  74. methods:
  75. upload() - uploads the file.
  76. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.