Essential PHP File and Directory Functions Guide

php file functionsphp file operationsphp file handlingphp directory managementphp file upload
Published·Modified·

1. Check if File or Directory Exists

is_file() Function

is_dir() Function

file_exists() Function

  • file_exists() — Checks whether a file or directory exists. Returns TRUE if the specified file or directory exists; otherwise, returns FALSE. This function combines the functionality of the two functions above.
  • More information: PHP file_exists() Function

2. Reading Files

file_get_contents() Function

fread() Function

Example of reading a file:

<?php
 $file = fopen("test.txt","r");
 fread($file,filesize("test.txt"));
 fclose($file);
?>

More usage instructions: PHP fread() Function

3. Writing Files

fwrite() Function

Note: The original text incorrectly labeled this section as fread() again. This section covers writing files using fwrite().

Example:

<?php
 $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
 $txt = "Bill Gates\n";
 fwrite($myfile, $txt);
 fclose($myfile);
?>

More information: PHP File Creation/Write

file_put_contents() Function

4. Create, Delete, and Copy Directories

mkdir() Function (Create Directory)

rmdir() Function (Delete Directory)

unlink() Function (Delete File)

copy() Function (Copy File)

  • Syntax: copy(source,destination)
  • Return value: Copies the file from source to destination. Returns TRUE on success or FALSE on failure.
  • More information: PHP copy() Function

rename() Function

  • rename() — Renames a file or directory.
  • Syntax: rename(oldname,newname,context)
  • Return value: Returns TRUE on success or FALSE on failure.

move_uploaded_file() Function

  • move_uploaded_file() — Moves an uploaded file to a new location.
  • Syntax: move_uploaded_file(file,newloc)
  • Return value: Returns TRUE on success or FALSE on failure.