Search code examples
phpappendfwrite

php fwrite append not working


Hello I am trying to make a script that is based on HTML post and basic PHP.

I have 1 input on HTML, and I have this PHP code:

<?php echo'h'?>

One of my friends said that if I changed the w to an it would create a new line so I changed it and it is still not working.

Basically what I am trying to do is that when they enter the text box any word, it writes that word to the text document, but the second time it won't create a new line, I just want to create a new line.

Here is my full code:

<?PHP
    $file_handle = fopen("sample.txt", "r");
    $file_contents = $_POST['f1'];
    fwrite($file_handle, $file_contents);
    fclose($file_handle);
    print "file created and written to";
?>

Solution

  • There is also other seemingly simpler functions by the names: file_put_contents() and file_get_contents(), which could be used (in your case) to make things a little easier to handle. The Code below shows the use of file_put_contents() and it's kin: file_get_contents() to accomplish the task.

        <?php
    
            $fileName       = "sample.txt";
    
            // GET THE TEXT TYPED-IN BY THE USER...         
            // ONLY YOU KNOW THE WAY TO GET THIS VALUE BUT WE CAN ASSUME (FOR NOW)          
            // THAT IT IS COMING FROM THE POST VARIABLE AND HAS THE NAME: input
            $input          = isset($_POST['input']) ? $_POST['input'] : null;
    
            // FIRST TRY TO SEE IF THE FILE EXIST, OTHERWISE CREATE IT
            // HOWEVER; WITH JUST AN EMPTY CONTENT
            if(!file_exists($fileName)){
                file_put_contents($fileName, "");
            }           
    
            // DO THE SAVING ONLY IF WE HAVE ANY INPUT (STRING) TO SAVE
            if($input){
                // GET THE CURRENT CONTENTS OF THE FILE...
                $fileContent    = file_get_contents($fileName);
    
                // ADD THE INPUT TO THE CURRENT CONTENTS OF THE FILE (WITH A NEW LINE)
                $fileContent   .= "\n{$input}";
    
                // SAVE THE MODIFIED CONTENT BACK AGAIN...
                $bytesSaved     = file_put_contents($fileName, $fileContent);
    
                // IF THE FILE WAS SUCCESSFULLY WRITTEN... THEN...
                // DISPLAY A MESSAGE TO THAT EFFECT
                if($bytesSaved){
                    print "file created and written";
                }
    
            }