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
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);  
?>

Link to comment
Share on other sites

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);
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.