Unexpected space at the beginning of the file

For my PHP courses I have to create a notepad that starts with a sample of text, when I edit it and click on the save button, the text inside the file is edited and saved. Therefore, if I refresh my page / open the file directly, I have new content edited by the displayed user.

This works, but I have some unexpected place in my file.

If I put the first character in the first line “sample text”, I will not see “sample text”, but instead:

sample text 

And this is only for the first line, what if I edited the file manually or with my page. All next lines begin with the first characters.

Below is my notes.txt file (where are my notes) after editing from a web page:

 Mes jeux préférés:
 => Fallout 3
 => Natural Selection 2
 =&#6 2; L4D2 

I do not see any weird character at the beginning of the file.

index.php:

 <?php define('FICHIER_DE_NOTES', 'notes.txt'); $fichier = fopen(FICHIER_DE_NOTES, 'r+'); if (array_key_exists('note', $_POST)) { $note = filter_var($_POST['note'], FILTER_SANITIZE_SPECIAL_CHARS); ftruncate($fichier, 0); fseek($fichier, 0); fputs($fichier, $note); $updateMessage = 'Vos notes ont été sauvegardés!'; } else { $note = ''; while ($ligne = fgets($fichier)) { $note = $note . $ligne; } } fclose($fichier); include 'index.phtml'; ?> 

And my index.phtml:

 <html lang="en"> <head> <meta charset="UTF-8"> <title>Bloc Note</title> </head> <body> <h1>Bloc Note</h1> <form method="post" action="index.php" > <p>Voici votre bloc note. Ajoutez-y du texte et cliquer sur "Sauvegarder".</p> <textarea id="textarea" name="note" rows="16" cols="50"> <?= $note ?> </textarea> <br/><br/> <label> <input type="submit" value="Sauvegarder"> </label> <?php if (isset($updateMessage)) { echo $updateMessage; } ?> </form> </body> </html> 

I am using vim and PHP5.

Tell me if you need more information.

+6
source share
3 answers

Or update your html:

 <textarea id="textarea" name="note" rows="16" cols="50"><?php echo $note ?></textarea> 

Or in your php script:

 if (array_key_exists('note', $_POST)) { $_POST['note'] = trim($_POST['note']); //added this line $note = filter_var($_POST['note'], FILTER_SANITIZE_SPECIAL_CHARS); ftruncate($fichier, 0); fseek($fichier, 0); fputs($fichier, $note); $updateMessage = 'Vos notes ont été sauvegardés!'; } else { $note = ''; while ($ligne = fgets($fichier)) { $note = $note . $ligne; } } 
+1
source

Spaces come from your HTML:

 <textarea id="textarea" name="note" rows="16" cols="50"> <?= $note ?> </textarea> 

You should use the following:

 <textarea id="textarea" name="note" rows="16" cols="50"><?php echo $note ?></textarea> 
+5
source

This is due to extra spaces in the tag of your HTML file:

  <textarea id="textarea" name="note" rows="16" cols="50"> <?= $note ?> </textarea> 

Try this:

  <textarea id="textarea" name="note" rows="16" cols="50"><?= $note ?></textarea> 
+3
source

All Articles