简体   繁体   English

PHP:表单到txt文件

[英]PHP: Form to txt file

I have been developing a testing website that uses a PHP script to dump data into a txt file for a no database option. 我一直在开发一个测试网站,该网站使用PHP脚本将数据转储到txt文件中,以提供无数据库选项。

My XAMPP setup says my post variable is undefined, although I'm sure it's not. 我的XAMPP设置说我的post变量是未定义的,尽管我确定不是。

I tried pre-creating the text file with the correct name (blank), and I have not messed with permissions on my Mac. 我尝试使用正确的名称(空白)预先创建文本文件,但是我并没有弄乱Mac上的权限。

How can I write this script? 如何编写此脚本?

Run this in your php file and you should see myfile.txt in the folder where your php file is. 在您的php文件中运行此文件,您应该在php文件所在的文件夹中看到myfile.txt。

$filepath = dirname(__FILE__) . '/myfile.txt'; //Current folder and this filename
$text = 'New Line of text'; //You input text

if(file_exists($filepath)) //If file created, append text
{
   file_put_contents($filepath, $text, FILE_APPEND);
}else{
   file_put_contents($filepath, $text);
}

Use var_dump($_POST); 使用var_dump($_POST); to check your post. 检查您的帖子。 Make sure the form is set to method='POST' . 确保将表单设置为method='POST'

Making sure you've set the permissions for the PHP saving to the text file and the file itself to writeable, something like this should fix your problem. 确保已将PHP的保存权限设置为文本文件,并且文件本身设置为可写,这样可以解决您的问题。

<form method="post" action="?submitted=true">
    <input type="text" name="itemA"/>
    <input type="text" name="itemB"/>
    <input type="text" name="itemC"/>
    <button type="submit"><button>
</form>
<?php
    if(isset($_GET['submitted']) && isset($_POST)) {
        $file = "textfile.txt"; 
        $text = "";
        foreach($_POST as $item) {
            $text .= $item;
        }

        if($text > "") {
            file_put_contents($file, $text);
        } else {
            echo "No items in POST!";
        }
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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