159

I have this script on one free PHP-supporting server:

<html>
<body>

<?php
$file = fopen("lidn.txt","a");


fclose($file);
?>

</body>
</html>

It creates the file lidn.txt, but it's empty.

How can I create a file and write something into it, for example the line "Cats chase mice"?

user664833
  • 18,397
  • 19
  • 91
  • 140
brilliant
  • 2,489
  • 8
  • 26
  • 28

9 Answers9

245

You can use a higher-level function like:

file_put_contents($filename, $content);

which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.

Docs: file_put_contents

Savageman
  • 9,257
  • 6
  • 40
  • 50
  • 4
    Just a sidenote, `file_put_contents()` works in PHP5 only. Doesn't seem like a problem in this case (your answer got accepter, after all), but there might still be a few hosts out there running PHP4.x . – Duroth Nov 20 '09 at 10:25
  • 3
    A very important sidenote: file_put_contents() is a memory nightmare in comparison to fopen(). I love to use it but when handling large files you want to be able to "stream" data into it. PHP will require a large multiple of final filesize as internal memory, so keep that in mind when using this function. For smaller amounts of data I'd recommend it for it's easy usage. – John Oct 12 '16 at 04:09
  • 2
    Then use file_put_contents($filename, $other_stream). It's the same as using stream_copy_to_stream-), which is very memory efficient. – Savageman Oct 12 '16 at 09:03
  • @Duroth it works only in PHP5 or it works only from PHP5 ? those are 2 different things. – Xsmael Jan 31 '20 at 17:26
  • 2
    @Xsmael Not in the distant past of 2009 ;) PHP7 wasn't around back then. But yeah, `put_file_contents()` was first introduced in PHP5, and has been included since, in later versions as well. – Duroth Feb 03 '20 at 09:28
  • 6
    To append to the file rather than over write: `file_put_contents($filename, $content, FILE_APPEND);` – Freedom_Ben Mar 11 '21 at 16:00
109

Consider fwrite():

<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
user664833
  • 18,397
  • 19
  • 91
  • 140
sathish
  • 6,705
  • 3
  • 30
  • 35
  • @sathish after writing to the file like above how do we read the file without closing the file ( `fclose($fp) `), I tried with `$fp = fopen('lidn.txt', 'w+');` , `$fp = fopen('lidn.txt', 'a+');` but neither of them worked – Kasun Siyambalapitiya Aug 21 '16 at 09:57
  • @KasunSiyambalapitiya See [rewind()](https://www.php.net/manual/en/function.rewind.php) – kmoser Mar 03 '21 at 02:08
26
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);

http://php.net/manual/en/function.fwrite.php

Pesse
  • 401
  • 3
  • 6
13
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);

You use fwrite()

lemon
  • 9,155
  • 7
  • 39
  • 47
  • after writing to the file like above how do we read the file without closing the file ( `fclose($fh)` ), I tried with `$fh = fopen('lidn.txt', 'w+');` ,` $fh = fopen('lidn.txt', 'a+'); ` but neither of them worked – Kasun Siyambalapitiya Aug 21 '16 at 09:59
11

It is easy to write file :

$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
RageZ
  • 26,800
  • 12
  • 67
  • 76
8

I use the following code to write files on my web directory.

write_file.html

<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>

write_file.php

<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);

// Show the msg, if the code string is empty
if (empty($cd))
    echo "Nothing to write";

// if the code string is not empty then open the target file and put form data in it
else
{
    $file = fopen("demo.php", "w");
    echo fwrite($file, $cd);

    // show a success msg 
    echo "data successfully entered";
    fclose($file);
}
?>

This is a working script. be sure to change the url in the form action and the target file in fopen() function if you want to use it on your site.

John Conde
  • 217,595
  • 99
  • 455
  • 496
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • 2
    I just started writing php but this looks like you are not just writing a text file, but you are writing a php code file onto your server, which could then be run immediately after by referencing the "demo.php" URL. Someone could write malicious PHP code to your server and immediately execute it, right? I assume this is so you could test your own codes but people should be warned of the risks of this particular implementation. (That being said, I like it and will us it myself) – RufusVS Jan 23 '18 at 16:47
8

Here are the steps:

  1. Open the file
  2. Write to the file
  3. Close the file

    $select = "data what we trying to store in a file";
    $file = fopen("/var/www/htdocs/folder/test.txt", "w");        
    fwrite($file, $select->__toString());
    fclose($file);
    
Augusto
  • 2,125
  • 18
  • 27
user10603371
  • 81
  • 1
  • 1
7

In order to write to a file in PHP you need to go through the following steps:

  1. Open the file

  2. Write to the file

  3. Close the file

    $select = "data what we trying to store in a file";
    $file = fopen("/var/www/htdocs/folder/test.txt", "a");
    fwrite($file  , $select->__toString());
         fclose($file );
    
Adam Richardson
  • 2,518
  • 1
  • 27
  • 31
6

fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead. Article

file_put_contents(file,data,mode,context):

The file_put_contents writes a string to a file.

This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure.

fwrite(file,string,length):

The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length, whichever comes first.This function returns the number of bytes written or FALSE on failure.

A.D.
  • 2,352
  • 2
  • 15
  • 25