handleUpload function to deal with file uploads in CakePHP


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



Copy this code and paste it in your HTML
  1. KEEP FOR LATER USE!
  2. $error = $this->handleFileUpload($importFile, $importFile['name']);
  3.  
  4. function handleFileUpload($fileData, $fileName)
  5. {
  6. $error = false;
  7. //Get file type
  8. $typeArr = explode('/', $fileData['type']);
  9.  
  10. print_r($typeArr);
  11. //If size is provided for validation check with that size. Else compare the size with INI file
  12. if (($this->validateFile['size'] && $fileData['size'] > $this->validateFile['size']) || $fileData['error'] == UPLOAD_ERR_INI_SIZE)
  13. {
  14. $error = 'File is too large to upload';
  15. }
  16. elseif ($this->validateFile['type'] && (strpos($this->validateFile['type'], strtolower($typeArr[1])) === false))
  17. {
  18. //File type is not the one we are going to accept. Error!!
  19. $error = 'Invalid file type';
  20. }
  21. else
  22. {
  23. //Data looks OK at this stage. Let's proceed.
  24. if ($fileData['error'] == UPLOAD_ERR_OK)
  25. {
  26. //Oops!! File size is zero. Error!
  27. if ($fileData['size'] == 0)
  28. {
  29. $error = 'Zero size file found.';
  30. }
  31. else
  32. {
  33. if (is_uploaded_file($fileData['tmp_name']))
  34. {
  35. //Finally we can upload file now. Let's do it and return without errors if success in moving.
  36. if (!move_uploaded_file($fileData['tmp_name'], WWW_ROOT.'/files/'.$fileName))
  37. {
  38. $error = true;
  39. }
  40. }
  41. else
  42. {
  43. $error = true;
  44. }
  45. }
  46. }
  47. }
  48. return $error;
  49. }
  50.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.