Working with files and folders in Magento2

Working with files and folders in Magento2

Magento® 2 offers you a bunch methods for file and folder operations, which allow you to implement quality modules in a short time. Especially if you are planning to publish modules on the Magento Marketplace you have to use those functions, otherwise you won’t meet Magento’s coding standards. In order to have access to cool functions like mkdirRecursive, deleteDirectory or changePermissionsRecursively simply inject \Magento\Framework\Filesystem\Driver\File in your constructor.

Once you have re-compiled your code, you should be able to use those functions in your modules like below.

More functions are listed below.

1. Check if the file or folder exists on the file system.

2. Returns information like ctime and mtime or sizeatimeuid and gid.

3. Check if a file is readable

4. Check if path is a file ( not folder )

5. Check if path is a directory ( not a file )

6. Get content of a regular file

7. Check if a regular file is writable ( not a folder )

8. Return the parent directory of a path

9. Create a new directory with specific permissions

10. Create a new directory recursively

11. Reads a directory and returns an array with all paths of its sub-directories

12. Search for a path

13. Rename a regular file or a directory

14. Copy a file from A to B

15. Create a symlink

16. Delete a regular file ( not a file )

17. Delete a directory recursively

18. Change permissions of a directory

19. Change permissions of a directory and file recursively

20. Manipulate the access and modification time of a file

21. Write content to a file

22. Opens a file like fopen

23. Returns a line from the given handle

24. Reads a file like fread.

25. Reads a CSV file like fgetcsv

26. Returns position of a pointer like ftell

27. Seeks to a specific offset like fseek

28. Returns true if pointer is at the end of a file

29. Close a file

30. Write to a file like fwrite

31. Write one row to a CSV file

32. Flush output of a file. See fflush.

33. Lock a file before write content to a file

34. Unlock a file after all file manipulations are done

35. Return a absolute path

36. Fixes a path separator

37. Reads a directory recursively and returns paths as an array

38. Return the real path like realpath

39. Returns a path for link


Leave a Reply

Your email address will not be published. Required fields are marked *