Advertisement
Danack

ensureDirectoryExists

Feb 3rd, 2014
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. function ensureDirectoryExists($filePath) {
  2. $pathSegments = array();
  3.  
  4. $slashPosition = 0;
  5. $finished = false;
  6.  
  7. while ($finished === false) {
  8.  
  9. $slashPosition = mb_strpos($filePath, '/', $slashPosition + 1);
  10.  
  11. if ($slashPosition === false) {
  12. $finished = true;
  13. }
  14. else {
  15. $pathSegments[] = mb_substr($filePath, 0, $slashPosition);
  16. }
  17.  
  18. $maxPaths = 20;
  19. if (count($pathSegments) > $maxPaths) {
  20. throw new \Exception("Trying to create a directory more than $maxPaths deep. What is wrong with you?");
  21. }
  22. }
  23.  
  24. foreach ($pathSegments as $segment) {
  25. if (file_exists($segment) === false) {
  26. //echo "Had to create directory $segment";
  27. $result = mkdir($segment);
  28.  
  29. if ($result == false) {
  30. throw new \Exception("Failed to create segment [$segment] in ensureDirectoryExists($filePath).");
  31. }
  32. }
  33. }
  34.  
  35. return true;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement