Question

I have this drop down menu:

<select name="location" id="location"> 
  <option value="empty" selected disabled></option>
  <option value="Toronto">Toronto</option>
  <option value="Pittsburgh">Pittsburgh</option>
  <option value="NewYork">New York</option>
</select>

I want to designate which .txt file will be written to when a user types into the textarea and hits submit.

<form name="writetolocation" method="post" action="Location.php">
<textarea cols="100" rows="3" name="writetolocation" placeholder="What's next?"></textarea>
<br>
<input type="submit" value="Submit" />
</form>

My .php thus far:

<?php
chmod("test.txt", 0766);
$writenext= $_POST['writenext'];
//the data
$next = "$writenext\n";
//open the file and choose the mode
$fh = fopen("test.txt", "a");
fwrite($fh, $next);
//close the file
fclose($fh);
?>

How do I set the variable to designate what .txt file to write to instead of using test.txt?

Was it helpful?

Solution

Try this:

<?php
    $location = $_POST['location'];
    $writenext = $_POST['writenext'];

    // prevent scripts
    $writenext = htmlentities($writenext);

    $file = '/path-to-textfile/'.$location.'.txt';

    $current_content = file_get_contents($file)." \n\n";

    $combined_content = $current_content.$writenext;

    $fh = fopen($file, "w");
    fwrite($fh, $combined_content);
    fclose($fh);

    header('Location: 'send-somewhere.php');
?>

It get the content of the existing file... adds a couple of breaks... and then adds the new content and rewrites the file with the new content added.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top