php post to variable and then append to txt [closed]

不羁岁月 提交于 2019-12-25 06:55:39

问题


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;



来源:https://stackoverflow.com/questions/21272192/php-post-to-variable-and-then-append-to-txt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!