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.
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.