Jump to content

Update txt file with PHP


gilgimech

Recommended Posts

What I'm tying to do is update a txt file using php.

 

the form:

<?php 
$file=fopen("news.txt","r") or die("Cannot open"); 
fclose($file); 
?> 

<form action="../includes/news_update.php" method="post">
<textarea rows="25" cols="40" name="content">
<?php echo $file ?>
</textarea><br>
<input type="submit" value="Submit"> 
</form>

 

update_news.php:

<?php
$content = $_POST["content"]; 
$file=fopen("news.txt","w") or die("Cannot open");
fwrite($content); 
fclose($file);  
?>

 

what I want to happen is the text from the file to populate the form field.

 

Edit the field then post it to the file.

 

I can't seem to get any of it to work.

Link to comment
https://forums.phpfreaks.com/topic/197034-update-txt-file-with-php/
Share on other sites

Your problem is that fopen does not return the content of the file, so $file won't contain what you're expecting. Instead to you need to use fread. If you want to get the full content of the file you can do something like this:

 

<?php 
$fp = fopen("news.txt","r") or die("Cannot open");
$file = fread($fp, filesize('news.txt'));
fclose($fp); 
?>

 

The problem with your updating is that for fwrite you need to pass the resource returned by fopen ($file, in your case).

 

<?php
$content = $_POST["content"]; 
$file=fopen("news.txt","w") or die("Cannot open");
fwrite($file, $content); 
fclose($file);  
?>

Well then that means your news.txt file contains nothing. To fix this before reading from the make sure there's actually something to read, like so:

 

<?php
if(($filesize = filesize('news.txt')) > 0)
{
    $fp = fopen("news.txt","r") or die("Cannot open");
    $file = fread($fp, $filesize);
    fclose($fp);
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.