user3956566
user3956566

Reputation:

Writing post values to a text file

I am trying to append a string to a text file.

The file users.txt is in the same folder as the php file.

$fname=$_POST['fname'];

$message = "name is :" . $fname. "\n";
if (isset($_POST['submit'])) {
    if ( file_exists("users.txt")) {
        $fp = fopen ("users.txt", "a");
        fwrite($fp, $message);
        fclose($fp);
    } else {
        echo'<script type="text/javascript">alert("file does not exist")</script>';
    }
}

It is not throwing the message error, nor is it writing to the file.
What have I done wrong?

My form:

<form onsubmit="return ValidateInputs();" action="contact.php" method="post"  id="contactForm" >
          <input class="input" type="text"  name="fname" id="fname"  />
          <input    type="submit" value="submit" name="submit"  />
</form>

nb. this form does submit.. it will send the message to me in an email.

Upvotes: 1

Views: 3677

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

The problem with your PHP handler is that the fname variable was not defined.

This was added $fname=$_POST['fname'];

<?php

$fname=$_POST['fname'];

$message = "name is :" . $fname . "\n";
if (isset($_POST['submit'])) {
    if ( file_exists("users.txt")) {
        $fp = fopen ("users.txt", "a");
        fwrite($fp, $message);
        fclose($fp);

echo "Success";

    } 

else {
       echo'<script type="text/javascript">alert("file does not exist")</script>';
    }
}

?>

Footnote: Additional permissions may be required in order to write contents to file. CHMOD 644 is usually the standard permissions setting, however certain servers require 777.

Via FTP and if there's a window where you can manually type in a command, by typing in chmod 644 users.txt or chmod 777 users.txt in your FTP software used.

Additional information on how to chmod files, may be obtained by visiting the GoDaddy Web site for Windows-based hosting services.


Upvotes: 3

Ali Gajani
Ali Gajani

Reputation: 15091

This works completely on my localhost. I haven't recreated the full scenario with your HTML but it works now. Just remember to set the file permissions to read/write and also make sure you do it one step at a time. For example, start off with this code and make sure you get the file name file.txt with the text you wanted. Then take it to the next level by including the HTML bit.

<?php
$fname = "Skippy";
$message = "name is :" . $fname. "\n";
$file = 'file.txt';
$fd = fopen($file, "a");

if ($fd) { 
    fwrite($fd, $message . "\n");   
    fclose($fd); 
}

?>

Upvotes: 3

Related Questions