Basic PHP File Handling — Create, Open, Read, Write, Append, Close, and Delete

By  on  

I don't do a great deal of file handling in my PHP code -- most of my customers don't have a need for it or there's no room for file creation in the already tight budget. On the rare occasion that I do need to manipulate files, I keep the following tip sheet.

Create a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file

Open a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //open file for writing ('w','r','a')...

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);
//write some data here
fclose($handle);

Delete a File

$my_file = 'file.txt';
unlink($my_file);

Recent Features

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

  • By
    Rotate Elements with CSS Transformations

    I've gone on a million rants about the lack of progress with CSS and how I'm happy that both JavaScript and browser-specific CSS have tried to push web design forward. One of those browser-specific CSS properties we love is CSS transformations. CSS transformations...

  • By
    Elegant Overflow with CSS Ellipsis

    Overflow with text is always a big issue, especially in a programmatic environment. There's always only so much space but variable content to add into that space. I was recently working on a table for displaying user information and noticed that longer strings were...

Discussion

  1. your work is very good,but need your in creating my website about cricket

  2. sebouneeeet

    To avoid warnings, not forget if(!file_exists(‘myfile.txt’)) ;)

  3. To avoid warnings, not forget if(!file_exists(‘myfile.txt’)) ;)
    your work is very good,but need your in creating my website about cricket

  4. Max

    Simple, but usefull!

  5. TitoChhabra

    Hello Everyone,
    File handling functions in PHP are extremely useful and userfriendly.PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files through the use of these functions…………… for more details please check out the following link….

    http://mindstick.com/Articles/07d7e4cf-b11c-49ea-8f4f-27c2e7f67c09/?File%20Handling%20in%20PHP

    Thanks !!!!

  6. Quite useful! Better to add the modes of the files. So that a person can understand more about php file handling… Thanks

  7. Bobo

    This is basic stuff. How about a script for updating a record in an ASCII flat file?

  8. jeet

    so useful for freshers in php

  9. Gary Paul

    Once again, I need a question answered and I find my way to David’s site. Thanks for all your help.

    Gary

  10. Some Guy

    Nice and concise! Definitely bookmarking. +1

  11. Some Guy

    Just found something out thought I’d post here for everyone else,
    To read a file line by line use fgets($file_handle)

    $file_handle = fopen(“myfile”, “r”);
    while (!feof($file_handle)) {
    $line = fgets($file_handle);
    echo $line;
    }
    fclose($file_handle);

  12. Saleem

    so useful for freshers in php

  13. Nice tutorial an am preparing this and i have an Interview next week :-)

  14. Thanks for making this nice tutorial and i am learning this. I only know to handle file via Control Panel i will learn it and try all those in a local server first

  15. Short and to the point, thanks, exactly what I was looking for. Much easier to delete a file than I thought, but what are your thoughts on security? Does this have any gaping security holes?

  16. Braydon

    Ok I have the code

    $my_file = 'file.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
    $data = 'This is the data';
    fwrite($handle, $data);
    

    And When I See if it works I geta

    Parse error: syntax error, unexpected '$my_file' (T_VARIABLE)
    
    • Anup Tiwari

      You’re missing a semicolon at the end.

  17. Bolivia Diablo

    Braydon, you’re probably missing a semi-colon in the line that comes before the code shown in your comment.

  18. Adam

    how come my output file has bo breaks? it is writing everything as a single line.

  19. Adam

    how come my output file has no breaks? it is writing everything as a single line. I want output like this:

    Line1

    Line2:

    Line3

    ……..

    • You Have to use This don’t use \n

      $data = ‘This
      is
      the
      data’;

    • Actually, using \n does work but you need to use “\n”, not ‘\n’.

  20. raja rajan

    hmm.make it simple

  21. your code doesn’t work am getting this error

    SQLSTATE[HY000] [2002] No such file or directory
    Warning: fopen(user_images/536974.txt): failed to open stream: Permission denied in /opt/lampp/htdocs/story_yako/addnew.php on line 31
    Cannot open file: user_images/536974.txt
    
  22. $upload_dir = 'user_images/'; // upload directory
    $random_name= rand(1000,1000000)."."."txt";
    $my_file = $upload_dir.$random_name;
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
    $data = $userjob;
    fwrite($handle, $data);
    fclose($handle)
    

    This is my code

  23. Chin-Chin everybody )
    Tell me please how to change directory for my file at this code :

    'file.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //open file for writing ('w','r','a')...
    

    Thank you very much!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!