Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected space at the begining of file

Tags:

php

For my PHP courses I have to create a note pad which start with a sample text, when I edit it and click on the save button, the text inside the file is edited and saved. So if I refresh my page / open the file directly I have the new content edited by the user displayed.

It works, but I have some unexpected space in my file.

If I put at the first character on the first line "sample text", I'll not see "sample text" but instead:

      sample text 

And that's only for the first line, what ever if I edited the file manually or with my page. All the next lines start at the first characters.

Below my notes.txt file (where my notes are) after an edit from the web page:

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

I don't see any strange character in 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 use vim and PHP5.

Tell me if you need more information.

like image 492
Kevin 'Koshie' GASPARD Avatar asked Jun 28 '16 10:06

Kevin 'Koshie' GASPARD


2 Answers

The whitespace comes 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>
like image 186
Jamie Bicknell Avatar answered Nov 15 '22 16:11

Jamie Bicknell


This is happening because of extra white spaces in the tag of your HTML file:

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

Try to do like:

    <textarea id="textarea" name="note" rows="16" cols="50"><?= $note ?></textarea>
like image 3
Sharry India Avatar answered Nov 15 '22 16:11

Sharry India