Checking whether a file or a folder exists
The file_exists() function returns TRUE if a provided file or directory exists on the server. This can be used to test for the presence of a file before doing anything with it:
if (file_exists('somefile.ext')) { // do something }
if (file_exists('somedirectory')) { // do something }
Creating a directory
To create a directory:
mkdir('directory_name');
You can also create nested subdirectories like this:
mkdir('folder_01/subfolder', 0, TRUE);
Copying a file
To copy a file from one folder to another, just use the copy or rename function respectively:
$oldFilePath = './assets/dir1/photo.jpg'; $newFilePath = './assets/dir2/photo.jpg'; copy( $oldFilePath , $newFilePath ); // copy the file
Moving a file or directory
To move a file or directory from one folder to another, just use the copy or rename function respectively:
rename( $oldFilePath , $newFilePath ); // move the file
Deleting a file
To delete a file, just use the unlink function:
unlink($oldFilePath);
Important notice: This function deletes files only, not folders.
Writing to file
Finding the contents of a directory
To find all of the contents of a directory, the easiest option is to use the scandir() function:
$files= scandir('./directory');
print_r($files);
The output from the above will look something like this:
Array
(
[0] => .
[1] => ..
[2] => 1.jpg
[3] => 2.gif
[4] => 3.png
[5] => bar.txt
[6] => baz
[7] => foo.txt
[8] => link2foo.txt
)
To exclude the . and .. directory aliases you can do this:
$files = array_slice(scandir('./directory'), 2);
print_r($files);
The output from the above will look something like this:
Array
(
[0] => 1.jpg
[1] => 2.gif
[2] => 3.png
[3] => bar.txt
[4] => baz
[5] => foo.txt
[6] => link2foo.txt
)