如何将输入上传到 php 中的文本文件

How to upload input to a text file in php

我想使用php将文本框中的内容上传到文本文件中。但也只有当字符串包含特定模式时才应写入它们。

这是我的 php 代码

<?php

$data = $_POST["text"];
public function copy(){
    if (strpos($data, '123') !== false){
    $myfile = "uploads/mydata.txt";
    $fh = fopen($myfile, 'w') or die("can't open file");
    fwrite($fh, $data);
    fclose($fh);
    }
}
?>

它在第 4 行说出乎意料 public。 我的表格是:

    <?php require_once('tally.php') ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title>
    </title>
    </head>
    <body>
    <form action="index.php" method="post">
        Input the first record
        <input type="text" name="text">
        <input type="submit" name="submit" action="submit">
        Submit
        </submit>
    </form>
    </body>
    </html>

感谢您的帮助

如果此函数不在 class 中,请删除单词 public。

public function copy(){

变成

function copy(){

为什么要用fopen,直接用file_put_contents。

输入的名称是文本,在 php 中您正在尝试接收 $_POST['data']。 将输入名称更改为数据或更改 php 代码并获取 $_POST['text'].

您的提交按钮也不符合 xhtml 或 html5 标准。将其更改为不需要结束标记或附加文本。

我看不到你在哪里调用复制函数。

代码应该是这样的。

<?php

$data = $_POST["data"];
if(!empty($data)) {
    copy2($data);
}
function copy2($data){
    if (strpos($data, '123') !== false){
    $myfile = "uploads/mydata.txt";
    $fh = fopen($myfile, 'w') or die("can't open file");
    fwrite($fh, $data);
    fclose($fh);
    }
}
?>

HTML 是这样的:

<?php require_once('tally.php') ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title>
    </title>
    </head>
    <body>
    <form action="index.php" method="post">
        Input the first record
        <input type="text" name="text">
        <input type="submit" value="submit">
    </form>
    </body>
    </html>

没有与数据关联的标签。请添加:

 <input type="text" name="data">