2

Currently I'm working with forms, trying to send a form submission to a text file. However, when I set the form action to my PHP script: action="saveScript.php, it redirects me to the PHP script's page in html.

HTML

<!DOCTYPE html>
<head>
<meta charset="UTF-8" lang="en">
<link rel="stylesheet" type="text/css" href="style/form.css">
</head>
<body>
<form method="POST" action="saveScript.php" id="twitterCardTest">
    <ul>
    <label for="fName">First Name: </label>
        <li><input type="text" id="fName" name="fName" size="5" maxlength="15"></li>
    <label for="lName">Last Name: </label>
        <li><input type="text" id="lName" name="lName" size="5" maxlength="15"></li>
    <label for="message">Message: </label>
        <li><input type="text" class="message" id="message" name="message" size="5" maxlength="140"></li>
    </ul>
        <input type="submit" name="submit" value="Submit Info" />
</form>
</body>
</html>

PHP

<?php

$file= fopen('test.txt', "a");
//retrieve existing file
$retrieve = file_get_contents($file);
$current = $_POST['fName'] . ' ' . $_POST['lName'] . "\n" . $_POST['message'] . "\n";
//record information inputted by user
$write =  fwrite($file, $current);
$fileSize = filesize('test.txt');

$saveFile = file_put_contents( '/htdocs/', $current, FILE_APPEND | LOCK_EX);

if($file === FALSE) {
    die('Error writing file');
}
else if  ($file != FALSE) {
    echo "Information written to file";
}
else {
    die('no post data to process');
}
fclose($file);
?>

Alternatively, I tried placing the PHP code into the html file after the body end tag. This resulted in the browser auto commenting the whole script out. I recently updated php using brew and I've configured my local web server to accommodate PHP. My question is how would I go about fixing this issue so my script is being read as php? In addition, why does this issue occur?

17
  • what do you mean, "php script's page in html"? You see the php source code in your browser? Commented Sep 16, 2015 at 20:30
  • It shows the PHP script on a separate page - the same way it would show if the php file was opened locally. Commented Sep 16, 2015 at 20:32
  • For starters you have four '}', but only three '{' Commented Sep 16, 2015 at 20:35
  • That has been fixed now. My apologies. Commented Sep 16, 2015 at 20:40
  • you're calling fwrite() without ever having fopen()'d the file in the first place. you're slurping the entire file into memory with file_get_contents(), adding your post data, then APPENDING that whole file, so every time you try to run this script, you'll be doubling the file's size, and then some. Commented Sep 16, 2015 at 20:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.