阅读时文本未更改

时间:2019-06-12 17:33:27

标签: php

我正在尝试创建一个交互式程序,用户可以使用文本文件在文本框中提出问题。但是我还处于早期阶段,可以用两行内容创建文本文件,其中之一就是问题和答案。 。我有两个php文件。其中一个创建文本文件。另一个应该被读取并在屏幕上显示,因为form action =“ questions.php”。但是由于某些原因,文本显示但没有改变

j.php文件1,它正在尝试创建文本文件。

<?php
if(isset($_POST['submit'])) {
    $question1 = $_POST['name'];
    $question2 = $_POST['age'];
    $file = fopen( "question.txt", "w+" ) or die( "file not open" );
    $s = $question1 . "," . $question2 . "\n";
    fputs($file, $s)or die("Data not written");

      }

else{
echo
'<center>
 <form action = "questions.php"  method = "post">
  Question you want ask the person <input  type  = "text" name="name"> <<br>
    Answer<input type = "text" name = "age"><br>
    <input type = "submit" name = "submit" value = "Make Question">
    </form>
    </center>';}
?>

预期输出将生成文件:question.txt

questions.php file2应该用来读取和显示新写入的数据。

<?php


$myfile = file_get_contents ("question.txt");
echo $myfile;

?>

预期输出,它应该读取新文本

1 个答案:

答案 0 :(得分:0)

基于更新后的问题,您有2个文件: j.php questions.php

  • j.php 负责显示表单并处理表单。
  • questions.php 负责显示表单的内容。

由于您的表单已发布到 questions.php ,因此您将跳过实际处理表单的过程。只需将表单的操作更改为:action="j.php",然后在处理后重定向到 questions.php

<?php
if(isset($_POST['submit'])) {

    $question1 = $_POST['name'];
    $question2 = $_POST['age'];

    $file = fopen( "question.txt", "w+" ) or die( "file not open" );
    $s = $question1 . "," . $question2 . "\n";
    fputs($file, $s)or die("Data not written");

    // Here - redirect to questions.php to display the contents.
    header('Location: questions.php');
    die;
}

<!-- You want to post this form to the processing file. -->
<form action="j.php" method="post">
...

或者,只需在单个文件中完成所有操作即可。

<?php
if (isset($_POST['submit'])) {

    $question1 = $_POST['name'];
    $question2 = $_POST['age'];

    $file = fopen("question.txt", "w+") or die("file not open");
    $s = $question1 . "," . $question2 . "\n";
    fputs($file, $s) or die("Data not written");

    header('Location: '.$_SERVER['PHP_SELF']);
    die;
}
?>

<h1>File Writer</h1>

<form method="post">
    <label>
        Question:
        <input type="text" name="name">
    </label><br>

    <label>Answer:
        <input type="text" name="age">
    </label><br>

    <input type="submit" name="submit" value="Make Question">
</form>

<hr>

The contents of the file are:

<!-- Suppressing a warning here with @. You shouldn't do this. -->
<?php echo @file_get_contents ("question.txt"); ?>