【问题标题】:How can I make individual people append text/strings to a .txt file I have on my server using php?如何让个人使用 php 将文本/字符串附加到我在服务器上的 .txt 文件中?
【发布时间】:2021-06-22 14:15:51
【问题描述】:

假设 user1 在文本框中写入“Hello”并提交,而 user2 在当天晚些时候写入“World”并提交。我如何对其进行编码,以便将他们的输入发送到我的 .txt 文件?因此 .txt 文件应如下所示:“Hello World”。回答这个问题可能有点复杂。如果是这样,谁能指出我正确的方向或给我任何好的链接/教程?第二个问题:我需要为此学习 MySQL 吗?

【问题讨论】:

  • file_put_contentsFILE_APPEND 可能有用。至于Do I need to learn MySQL - IMO 你最好使用数据库而不是文本文件,但这是一个基于意见的问题/答案
  • 请阅读How much research effort is expected of Stack Overflow users?。如果您只是对每个步骤进行一些研究(例如“php 中的表单”、“使用 php 将文本存储在文件中”等),您会发现 很多 教程。 Mysql 是一个数据库,与您的要求没有任何关系(尽管我同意第一条评论,但最好使用数据库而不是文本文件)

标签: php html server txt


【解决方案1】:

这可能会有所帮助...

  • index.php

    <?php
    if (!isset($_SESSION)) {
        session_start();
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
    <?php
    if (!empty($_SESSION)) {
        echo $_SESSION['msg'];
        session_unset();
    }
    ?>
    <form action="store.php" method="POST">
        <input type="text" name="inputText">
        <input type="submit">
    </form>
    </body>
    </html>

  • store.php
    <?php
    include_once 'TextStoreIntoFile.php';
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $addText = new TextStoreIntoFile();
        $addText->addTextIntoFile($_REQUEST['inputText']);
    }
  • TextStoreIntoFile.php
    <?php
    declare(strict_types=1);

    class TextStoreIntoFile
    {
        public function addTextIntoFile(string $data)
        {
            if (!isset($_SESSION)) {
                session_start();
            }
            $data = $data . ' ';
            $textAdded = file_put_contents('text.txt', $data, FILE_APPEND | LOCK_EX);
            if ($textAdded) {
                $_SESSION['msg'] = 'Text added into the file';
                header('Location: index.php');
            } else {
                $_SESSION['msg'] = 'Text not added!';
                header('Location: index.php');
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多