PHP File and Folder Management

Let's get Started...
Creating a Folder
For creating a folder with PHP first we have to check is the folder name that we are want to create is exist. If that folder is exist the server will not create the folder and return false. To check the folder is exist we use file_exist function.
If the related folder do not exist we can create the folder with the mkdir function. Below you can see the usage of mkdir function.
mkdir ( string $pathname, int $mode = 0777, bool $recursive = FALSE , resource $context ) : bool
- $pathname: This variable is required to specify the absolute path.
- $mode : This is an optional variable. This variable will set the permissions of created file and directory. Default value is 0777. Below table you can see permission parameters
- $recursive: Allows the creation of nested directories specified in the pathname
- $context: If you want to specify the additional context you can add it as resource in here.
Value | Permission |
---|---|
0 | cannot read, write or execute |
1 | can only execute |
2 | can only write |
3 | can write and execute |
4 | can only read |
5 | can read and execute |
6 | can read and write |
7 | can read, write and execute |
Now we copy a file from another directory into this new created folder. Below code block you can see copy function usage.
copy ( string $source , string $target ) : bool
Below code block lets make an example for copying the files. If copied files exist in target location copied file will be overwritten on same file. Be carefull in this.
Now we know the copying the files. Lets see how can we move a file from another directory. Below code block will show the usage of the required function to move a file in the server.
The are two options for this. If the file is at the server we will use the rename function. If we want to move an uploaded file we will use the move_uploaded_file function.
move_uploaded_file ( string $fileSource, string $target) : bool
Below code block will move the file under folder that named with year and month. It will chechk the folder is exist and if do not exist the related directory will be created before moving. After creating the folder the file will be moved.
That is all in this article.
Thanks for reading.
Have a nice file/folder processing.
Burak Hamdi TUFAN