views:

50

answers:

2

Hi I am trying to create some code that first reads the existing contents of the file in and then adds the new line of code on a new line but the code i am using just adds it on the new text on to the already existing line instead of the new line...

Here is the code i am using:

<?php

$id = $_GET['id'];

$userfile = "user1.txt";
$fo = fopen($userfile, 'r') or die("can't open favourites file");
$currentdata = fread($fo, filesize($userfile));
fclose($fo);
$fw = fopen($userfile, 'w') or die("can't open favourites file");
$currentprocessed = "$currentdata\n";
fwrite($fw, $currentprocessed);
fwrite($fw, $id);
fclose($fw);
?>

I have tried a whole range of different ideas but nothing has worked, any help would be appreciated.

+1  A: 

Instead of appending \n, concatenate the constant PHP_EOL which is always the correct newline character for the current platform.

It might also be an issue with the program you're using to open the text file with. For instance, Notepad on Windows is incapable of understanding unix style newlines.

nikc
Reading the question I was thinking exactly that - Notepad on Windows doesn't show \n new lines, it's expecting \n\rYou might have luck with wordpad (ridiculous, I know) or download yourself a textpad and use it for everything (http://www.textpad.com/)
Raine
+1  A: 

Line endings per OS

Unix / Linux
\n

DOS / Windows
\r\n

Invalid
\r and \n\r


The value of PHP_EOL constant depends on the platform php is running on.
It doesn't detect the line-endings in the current file or anything magic.

Bob Fanger
Didn't mac used to use `\r`? Or something? I thought I remembered `\r` being in use somewhere
Carson Myers
In the OS 9 days `\r` was used, but since Mac OSX it's `\n`. See http://en.wikipedia.org/wiki/Newline for more info.
Bob Fanger