Commonly Used File Operation Functions in PHP

Publish: 2018-11-08 | Modify: 2018-11-08

1. Determine if a file/directory exists

is_file function

is_dir function

file_exists() function

  • file_exists() function checks whether a file or directory exists. Returns true if the specified file or directory exists, false otherwise. It is like a combination of the previous two functions.
  • More information: PHP file_exists() function

2. Read a file

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 information: PHP fread() function

3. Write to a file

PHP fread() function

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/Writing

file_put_contents() function

4. Create directory/delete/copy

mkdir function, create directory

rmdir function, delete directory

unlink function, delete file

copy() function, copy file

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

rename() function

  • rename() function renames a file or directory.
  • Syntax: rename(oldname,newname,context)
  • Returns: Returns true if successful, false otherwise.

move_uploaded_file() function

  • move_uploaded_file() function moves an uploaded file to a new location.
  • Syntax: move_uploaded_file(file,newloc)
  • Returns: Returns true on success, false on failure.

Comments