Page 1 of 1

writting to a file adds an unwanted line break on top

Posted: Wed Dec 15, 2004 12:38 pm
by sebnewyork
Hi all
I'm trying to build a rudimentary (simple) content management system in PHP.
I have a input from with textfiled, and when submit is pressed, the content of the text filed writes itself into a 'text.htm'. It replaces the previous content.

here's the essential code:

Code: Select all

<?
phpfunction get_htmlspecialchars($given, $quote_style = ENT_QUOTES) {
   return htmlspecialchars(html_entity_decode($given, $quote_style), $quote_style);
}

if (isset ($_POST['submit'])) {
    if (!empty ($_POST['message'])) {
        if ($fp = fopen ("text.htm", 'w')) {
			if (ini_get ('magic_quotes_gpc')) {
				$data = stripslashes ($_POST['message']);
			} else {
				$data = $_POST['message'];
			}
			get_htmlspecialchars($data);
            fwrite ($fp, nl2br("$data"));
            fclose ($fp);
            header ('location: index.php');
        }
    }
}

?>
the problem is, each time I write new content, a new line break is added at the top of my "text.htm" file, so the more I update it, the more empty space is created at the top of the text.

I tried to replace:

fwrite ($fp, nl2br("$data"));

with:

fwrite ($fp, ("$data"));

thinking that this "nl2br" is responsable for adding an additional line break each time, but without it, all my other line breaks in "text.htm" desappear.

What should I do?

Posted: Wed Dec 15, 2004 12:47 pm
by rehfeld
if your writing in 'w' mode, it should start writing at the very beg of the file.

your problem must be because you are feeding additional line breaks when you submit the form.

you could take a look at trim() rtrim() and ltrim()

Posted: Wed Dec 15, 2004 12:54 pm
by sebnewyork
oh! I solved my problem it was very simple: not a PHP issue, but and html issue:
I have the following code in my form tag, for the textarea:

<textarea name="message" cols="40" rows="20" class="post" onSelect="storeCaret(this);" onClick="storeCaret(this);" onKeyUp="storeCaret(this);">
<?php
$original = file_get_contents ("text.htm");
$search = '<br />';
$replace = '';
$new_message = str_replace ($search, $replace, $original);
echo "$new_message";
?>
</textarea>

I previously had an empty line in this code, between the first line <textarea....> and the second <php?
this is what caused the text area to add an extra space each time.