php post to variable and then append to txt [close

2019-08-30 18:40发布

问题:

I'm having this problem where I can't manage to accomplish this simple script. Basically, I want to take a post from a form, assign it to a variable, and then append the variable to a preexisting example.txt file. I apologize for the lack of examples, I switched to my phone after I went out to dinner with my inlaws. Could anyone post a simple example andd allow me to build off of that foundation? thanks in advance

回答1:

The following should give you a foundation to start.

<?php

// Check to see if the form was submitted

if(isset($_POST['action']) && $_POST['action'] == 'add'){

    $file = 'example.txt';

    // Open the file to get existing content
    $current = file_get_contents($file);

    // Append a new person to the file
    $current .= $_POST['test'];

    // Write the contents back to the file
    file_put_contents($file, $current);
}

?>

<form method="POST">

    <!-- This becomes PHP variable $_POST['test'] -->
    <input type="text" name="test" /> 

    <input type="hidden" name="action" value="add" />
    <input type="submit" value="Add"/>
</form>

Check out http://us3.php.net/file_put_contents for more information.



回答2:

If your html form has a text field like this <input type="text" name="firstName" value="Name"> you can access that value in your php script using $_POST['firstName'];. If you want to append text in php, you can simply do it using "." Ex: $post_string = 'Ex:' . $post_string;