下面的php程序中文件处理概念的错误是​​什么?

时间:2015-11-25 08:50:22

标签: php html file-handling

每当我尝试使用创建按钮创建新的txtfile时,尽管文件已创建但数据未写入文件。我只是一个空白文件。什么是错误?

    <?php
    error_reporting(0);
    if(isset($_POST['sub']))
    {
        $fname=$_POST["txtfile"];
        $cont=$_POST['txtarea'];
        if($_POST['sub']=="create")
        {
            fopen($fname,"w");
            fwrite($fname, $cont);
        }
        else if($_POST['sub']=="read")
        {
            echo file_get_contents($fname); 
        }

        else if($_POST['sub']=="delete")
        {
            unlink($fname);
        }

        else if($_POST['sub']=="append")
        {
            $cont=$_POST['txtarea'];
            $fp=fopen($fname,"a");
            fwrite($fp,$cont);
        }
    }
    ?>

这是上面程序的html代码。我应该将用于读取文件的php代码插入到html中的textarea代码中。?

<!DOCTYPE html>
<html>
<h3>file handling concept</h3>
<style type="text/css">

#form{
    height: 200px;
    width: 400px;
    margin: 10px;
}
label {
    float: left;
    margin-right: 10px;
    width: 70px;
    padding-top: 5px;
    font-size: 15px;
}
#form input, #form textarea{
    padding: 5px;
    width: 306px;
    font-family: Helvetica, sans-serif;
    font-size: 15px;
    margin: 0px 0px 0px 0px;
    border: 2px solid #ccc;
}
#button input{
    float: right;
    margin: 5px;
    width: 60px;
    padding: 5px;
    border: 1px solid #ccc;
}   
</style>
<div id="form">
    <form method="POST" action="filehandling.php">

        <label for="name">Filename:</label>
        <input type="text" name="txtfile" placeholder="file-name.txt" />

        <label for="name">content:</label>
        <textarea name="txtarea" placeholder="write some content">

</textarea>
        <div id="button">
            <input type='submit' name='sub' value='create'>
            <input type='submit' name='sub' value='delete'>
            <input type='submit' name='sub' value='append'>
            <input type='submit' name='sub' value='read'>
        </div>
    </form>
</div>
</html>

2 个答案:

答案 0 :(得分:0)

我认为您应该在创建文件时使用句柄,如下所示。

if($_POST['sub']=="create")
{
    $fh = fopen($fname,"w");
    fwrite($fh, $cont);
    fclose($fh);
}

同样在else if($_POST['sub']=="append")中,无需再次定义$cont,因为它已使用相同的值进行定义。

所以

else if($_POST['sub']=="append")
        {
            $cont=$_POST['txtarea'];
            $fp=fopen($fname,"a");
            fwrite($fp,$cont);
        }

变为

else if($_POST['sub']=="append")
{
    $fp=fopen($fname,"a");
    fwrite($fp,$cont);
    fclose($fp);

}

答案 1 :(得分:0)

您的文件创建和编写方法应如下所示:

if($_POST['sub']=="create")
{
    $fp = fopen($fname,"wb");
    fwrite($fp,$cont);
    fclose($fp);
}