Jump to content

Problem with writing to text file


Psychophylus

Recommended Posts

I'm pretty new to PHP. I wrote this little code here:

$file = fopen("data.txt", "a+");$text = $_POST['text'];$data = fwrite($file, "$text <br>");require('data.txt');

How could I make this insert the text into the beginning of the file without writing over what's already there?

Link to comment
Share on other sites

$text = $_POST['text'];$existing_data = file_get_contents("data.txt");$new_data = $text . "<br>" . $existing_data;file_put_contents("data.txt", $new_data);require('data.txt');

Does that make sense?You can even shorten that still:

file_put_contents("data.txt", $_POST['text'] . "<br>" . file_get_contents("data.txt"));require("data.txt");

Link to comment
Share on other sites

Actually I didn't notice that, file_put_contents is a function in PHP 5 and later. It's not your browser by the way, it's the server that has PHP installed on it. If they upgraded to PHP 5, you could use that. But not a lot of servers have PHP 5 yet, it seems that most web hosts typically wait a few years to upgrade to any major version.This code is based on the php.net example for fwrite, with some modifications for your situation:

<?php$filename = 'data.txt';$text = $_POST['text'] . "<br>";// Let's make sure the file exists and is writable first.if (is_writable($filename)) {   if (!$handle = fopen($filename, 'wb')) {         echo "Cannot open file ($filename)";         exit;   }   // Read the existing text.   $old_text = fread($handle, filesize($filename));   // Write $text to our opened file.   if (fwrite($handle, $text . $old_text) === FALSE) {       echo "Cannot write to file ($filename)";       exit;   }      fclose($handle);}require_once("data.txt");?>

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

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...