PHP File Handling – CRUD

Quick tips, how to work with basic filesystem in PHP.

  • Create a File (implicitly creates file):
    $my_file = 'file.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
  • Open a File (open file for writing (‘w’,’r’,’a’)):
    $my_file = 'file.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
  • Read a File:
    $my_file = 'file.txt';
    $handle = fopen($my_file, 'r');
    $data = fread($handle,filesize($my_file));
  • Write to a File:
    $my_file = 'file.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
    $data = 'This is the data';
    fwrite($handle, $data);
  • Append to a File:
    $my_file = 'file.txt';
    $handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
    $data = 'New data line 1';
    fwrite($handle, $data);
    $new_data = "\n".'New data line 2';
    fwrite($handle, $new_data);
  • Close a File:
    $my_file = 'file.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
    fclose($handle);
  • Delete a File:
    $my_file = 'file.txt';
    unlink($my_file);
Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk