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 a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.