Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Working with Directoris and Files

By: FYICenter.com

Part:   1   2 

A collection of 8 tips on PHP functions for working with file systems:

  1. How To Create a Directory?
  2. How To Remove an Empty Directory?
  3. How To Remove a File?
  4. How To Copy a File?
  5. How To Dump the Contents of a Directory into an Array?
  6. How To Read a Directory One Entry at a Time?
  7. How To Get the Directory Name out of a File Path Name?
  8. How To Break a File Path Name into Parts?

How To Create a Directory?

You can use the mkdir() function to create a directory. Here is a PHP script example on how to use mkdir():

<?php 
if (file_exists("/temp/download")) {
  print("Directory already exists.\n");
} else {
  mkdir("/temp/download");
  print("Directory created.\n");
}
?>

This script will print:

Directory created.

If you run this script again, it will print:

Directory already exists.

How To Remove an Empty Directory?

If you have an empty existing directory and you want to remove it, you can use the rmdir(). Here is a PHP script example on how to use rmdir():

<?php 
if (file_exists("/temp/download")) {
  rmdir("/temp/download");
  print("Directory removed.\n");
} else {
  print("Directory does not exist.\n");
}
?>

This script will print:

Directory removed.

If you run this script again, it will print:

Directory does not exist.

How To Remove a File?

If you want to remove an existing file, you can use the unlink() function. Here is a PHP script example on how to use unlink():

<?php
if (file_exists("/temp/todo.txt")) {
  unlink("/temp/todo.txt");
  print("File removed.\n");
} else {
  print("File does not exist.\n");
}
?>

This script will print:

File removed.

If you run this script again, it will print:

File does not exist.

How To Copy a File?

If you have a file and want to make a copy to create a new file, you can use the copy() function. Here is a PHP script example on how to use copy():

<?php
unlink("/temp/myPing.exe");
copy("/windows/system32/ping.exe", "/temp/myPing.exe");
if (file_exists("/temp/myPing.exe")) {
  print("A copy of ping.exe is created.\n"); 
}
?>

This script will print:

A copy of ping.exe is created.

(Continued on next part...)

Part:   1   2 


Selected Developer Jobs:

More...