我无法存储用户'简单的.txt文件中的答案?

时间:2016-08-08 03:55:15

标签: php forms store

我是php的新手,所以我试图制作一个简单的多项选择测验应用程序,一次一个问题,所以当用户点击提交按钮时,它转到下一个问题所以问题是在不同的php文件中,所以我试图使用fopen,fwrite函数将答案存储在一个简单的answers.txt文件中,但问题是当我试图自己回答测验问题时...它没有创建answers.txt文件,所以我创建了它手动但它仍然是空的,这是第一个问题' php代码:

<?php 
if (isset($_GET['q1']) && !empty($_GET['q1'])) {
    $answer1 = $_GET['q1'];
    $heranswers = fopen("Nanswers.txt ", "a+");
    fwrite($heranswers, $answer1);
}
?>

那么这有什么不对?

2 个答案:

答案 0 :(得分:0)

在if循环中添加以下代码

if (is_writable($filename)) {

    if (!$handle = fopen($filename, 'a')) {
        echo "Cannot open file ($filename)";
        die(error_get_last());
    }

    // Write $answer1 to our opened file.
    if (fwrite($handle, $answer1) === FALSE) {
        echo "Cannot write to file ($filename)";
        die(error_get_last());
    }

    echo "Success, wrote ($answer1) to file ($filename)";

    fclose($handle);
} else {
    echo "The file $filename is not writable";
}

至少你会发现错误

答案 1 :(得分:0)

确保文件权限..它应该是可写的......

<?php

$answer1 = 10;
$filename = "Nanswers.txt";

// Let's make sure the file exists and is writable first.

if (is_writable($filename)) {

    if (!$handle = fopen($filename, 'a+')) {
        echo "Cannot open file ($filename)";
        die(error_get_last());
    }

    // Write $answer1 to our opened file.
    if (fwrite($handle, $answer1) === FALSE) {
        echo "Cannot write to file ($filename)";
        die(error_get_last());
    }

    echo "Success, wrote ($answer1) to file ($filename)";

    fclose($handle);
} else {
    echo "The file $filename is not writable";
}
?>