Reputation: 65
I am trying to have a user write something in the text box. Then the text is written ON A NEW LINE in a file called "list.txt". Then I want the whole file to be read on the website. That way it will be like a chat room or something. The trouble is, right now it is telling me "Unable to open file." I have checked and the file's permissions and every type of user has full access. List.txt is also in the same directory as the php file. Also, when it was able to open the file, it would not write it on a new line. I know that this can be done using "\n" or PHP.EOL but neither of them seemed to work and sometimes they would stop the site from running all in itself. Please help me figure out what is going on, thanks.
<html>
<p>
<form name="form1" method="post" action="test.php">
<input name="text" type="text">
<input type="submit" value="send" method="post">
</p>
<p>
<?php
$file = fopen("list.txt") or die ("Unable to open file!");
$text = $_POST['text'];//where the hell do you put the new line indicator: "\n"//
fwrite($file, $text) or die ("Cannot write!");
$print = fread($file,filesize("list.txt", "a+"));
fclose($file);
echo $print;
?>
</p>
<?php //figure out how to make this a button that clears the file
/*
$fp = fopen("list.txt", "r+");
// clear content to 0 bits
ftruncate($fp, 0);
//close file
fclose($fp);*/
?>
</html>
Upvotes: 1
Views: 1831
Reputation: 2934
Use file_put_contents
...
$file = 'list.txt';
$content = $_POST['text']."\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
file_put_contents($file, $content, FILE_APPEND);
As per the documentation
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
Upvotes: 1
Reputation: 792
You have the problem that your file will be locked for the time php write the content.
If you want to write at the same time, then you have a short time no access to your file. Thats the big problem of file based solutions. Database engines are made for that.
Upvotes: 0