简体   繁体   中英

How to store php form data to a web server in a plain text file?

I have an assignment that calls for data entries from a php form to be stored in a plain text file on the same web server. I created the php form page and the plain text file but I am unsure how to connect the two. I've searched the internet and tried multiple ways for about two hours now and no dice. The data entries have to accumulate in the plain text file too (1st person submits, and a 2nd person submitting can see 1st person's submission and so on).

I didn't add any of the code I've tried to the plain text file because none of them were working and I wanted to (in theory) simplify the process of not having to try and fix the code. I know that the plain text file needs some sort of code to retrieve the code from the php form but unsure what to try at this point. And yes I wrote permissions for the plain text file to be writable via FileZilla.

Here's my php form code:

<!DOCTYPE HTML> 
<html>
<head>
<title>Roy Feedback Form Assignment 7</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 

<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $likesErr = $howErr = $rateErr = "";
$name = $email = $comment = $likes = $how = $rate = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
 $nameErr = "Name is required";
} else {
 $name = test_input($_POST["name"]);
}


$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format"; 
}

if (empty($_POST["comment"])) {
 $commentErr = "Comments are required";
} else {
 $comment = test_input($_POST["comment"]);
}

if (empty($_POST["likes"])) {
 $likesErr = "Things you liked is required";
} else {
 $likes = test_input($_POST["likes"]);
}

if (empty($_POST["how"])) {
 $howErr = "How you got to our site is required";
} else {
 $how = test_input($_POST["how"]);
}

 if (empty($_POST["rate"])) {
 $rateErr = "Rating our site is required";
} else {
 $rate = test_input($_POST["rate"]);
}
}

function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
     .removeAttr('checked').removeAttr('selected');
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> 

<h2>Roy Feedback Form Assignment 7</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>

E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>

Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>

Things you liked:
<input type="radio" name="likes" value="Site design">Site design
<input type="radio" name="likes" value="Links">Links
<input type="radio" name="likes" value="Ease of use">Ease of use
<input type="radio" name="likes" value="Images">Images
<input type="radio" name="likes" value="Source code">Source code
<span class="error">* <?php echo $likesErr;?></span>
<br><br>

How you got to our site:
<input type="radio" name="how" value="Search engine">Search engine
<input type="radio" name="how" value="Links from another site">Links from another site
<input type="radio" name="how" value="Deitel.com website">Deitel.com website
<input type="radio" name="how" value="Reference from a book">Reference from a book
<input type="radio" name="how" value="Other">Other
<span class="error">* <?php echo $howErr;?></span>
<br><br>

Rate our site:
<select name="rate">
<option value="">- Please Select -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span class="error">* <?php echo $rateErr;?></span>
<br/><br/>

<input type="submit" name="submit" value="Submit"> 
<input type="reset" value="Reset">

</form>

</body>
</html>

And here's the plain text file code:

<!DOCTYPE html>
<html>
<head>
    <title>Roy Feedback Results Assignment 7</title>
</head>
<body>



</body>
</html>

Update 1 So I'm still having issues (sorry, I know it's like trying to teach PHP to a grapefruit). So when I use the following code nothing happens on the plain text page (as in the data isn't stored where I tell it to be):

function file_write($data, $feedback_results_html_only){
if(is_readable($feedback_results_html_only)){
    if(is_string($data)){
        return file_put_contents($feedback_results_html_only, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
    }//return an error message if the data isnt a string
}//return an error message if the file doesnt exist or isnt readable
}

However when I use the following code it at least places the "John Smith" name into the file (which is the first time I actually got it to somewhat work, hooray coding!):

<?php
$file = 'feedback_results_html_only.php';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Also I am aware that I didn't use the ".php" on the "feedback_results_html_only" in the first example of code (in update 1) because it created an error. Could I possibly try something like the second example (in update 1) instead to make it work?

$file = 'feedback_results_html_only.php'

Use file_put_contets

$relative_or_absolute_path = '../'; //relative folder up
$ext = '.txt'; //file can be with no extension at all or even *.php
$filename = 'plain_log';

$contents = '';
foreach($users as $user){
   $contents .= $user . '\n'; //a newline  
}

//execute

file_put_contents($relative_or_absolute_path.$filename.$ext, $contents, FILE_APPEND);

//FILE_APPEND is an optional flag // otherwise it will rewrite

You are looking for file_put_contents() . Simply collect the data and write it to your file. Here is the refined code:

PS: You could consider starting with the php code first :-)

<?php
  // define variables and set to empty values
  $nameErr = '';
  $emailErr = '';
  $commentErr = '';
  $likesErr = '';
  $howErr = '';
  $rateErr = '';
  $name = '';
  $email = '';
  $comment = '';
  $likes = '';
  $how = '';
  $rate = '';

if ($_SERVER["REQUEST_METHOD"] == "POST"){
   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
   }


  $email = test_input($_POST["email"]);
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Invalid email format"; 
  }

  if (empty($_POST["comment"])) {
    $commentErr = "Comments are required";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["likes"])) {
    $likesErr = "Things you liked is required";
  } else {
    $likes = test_input($_POST["likes"]);
  }

  if (empty($_POST["how"])) {
    $howErr = "How you got to our site is required";
  } else {
    $how = test_input($_POST["how"]);
  }

  if (empty($_POST["rate"])) {
    $rateErr = "Rating our site is required";
  } else {
    $rate = test_input($_POST["rate"]);
  }
}

function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
     .removeAttr('checked').removeAttr('selected');
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}



 //concatenate the data, then format and validate it then use this function to write it to your plain text file

function file_write($data, $pathtoplaintxtfile){
        if(is_string($data)){
            return file_put_contents($pathtoplaintxtfile, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
        }//return an error message if the data isnt a string
}
    ?>


    <!DOCTYPE HTML> 
    <html>
        <head>
            <title>Roy Feedback Form Assignment 7</title>
            <style>
                .error {color: #FF0000;}
            </style>
        </head>
       <body>
<h2>Roy Feedback Form Assignment 7</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>

E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>

Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>

Things you liked:
<input type="radio" name="likes" value="Site design">Site design
<input type="radio" name="likes" value="Links">Links
<input type="radio" name="likes" value="Ease of use">Ease of use
<input type="radio" name="likes" value="Images">Images
<input type="radio" name="likes" value="Source code">Source code
<span class="error">* <?php echo $likesErr;?></span>
<br><br>

How you got to our site:
<input type="radio" name="how" value="Search engine">Search engine
<input type="radio" name="how" value="Links from another site">Links from another site
<input type="radio" name="how" value="Deitel.com website">Deitel.com website
<input type="radio" name="how" value="Reference from a book">Reference from a book
<input type="radio" name="how" value="Other">Other
<span class="error">* <?php echo $howErr;?></span>
<br><br>

Rate our site:
<select name="rate">
<option value="">- Please Select -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span class="error">* <?php echo $rateErr;?></span>
<br/><br/>

<input type="submit" name="submit" value="Submit"> 
<input type="reset" value="Reset">

</form>

</body>
</html>

EDIT: file_put_contents() automaticly creates a file if it doesnt exist, remove is_readable file check.

EDIT: Usage -

$data = $name.$email.$comment.$likes.$how.$rate.
'This is just test data. If no other data is visible, then you didnt fill them out';
file_write($data, 'feedback_results_html_only.php')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM