PHP文件上传&编辑

时间:2018-04-26 12:33:33

标签: php html forms

我有一个网站,我正在为该网站制作内容管理系统。我需要上传.txt文件,然后才能在网站内编辑该文件。到目前为止我有这个:

<?php
        $myFile = fopen("welcome-content.txt", 'r');
        while (($buffer = fgets($myFile)) !== false) {
            echo "<p>";
            echo $buffer;
            echo "</p>";
        }
        fclose($myFile);
    ?>

这可以上传文件,但我必须将文件名称为“welcome-content.txt”,我希望能够从文件资源管理器中选择一个文件,上传它,然后能够编辑它。我是否正确地认为我需要一个HTML表单来选择文件?但就其他事情而言,我不确定从那里去哪里。

任何提示?

1 个答案:

答案 0 :(得分:1)

生成html表单以选择要上传的文件:

<form enctype="multipart/form-data" method="post" action="test_php.php">
   <input id="image-file" name="image-file" type="file" />
   <input type="submit" value="submit" id="submit" />
</form>

编写php代码来处理上传和修改文件:

<?php

if ( !isset($_FILES['image-file']['error']) || is_array($_FILES['image-file']['error']) ) 
{
    throw new RuntimeException('Invalid parameters.');
}

// Check $_FILES['image-file']['error'] value.
switch ($_FILES['image-file']['error']) 
{
    case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        throw new RuntimeException('Exceeded filesize limit.');
    default:
        throw new RuntimeException('Unknown errors.');
}

// Check filesize here. 
if ($_FILES['image-file']['size'] > 1000000) 
{
    throw new RuntimeException('Exceeded filesize limit.');
}
$filename = $_FILES['image-file']['name'];

echo "Filename is $filename <br>";

//Add new line
$f = fopen($filename,"a"); // Append mode
fwrite($f, "Added new line\n");
fclose($f);

echo "After modify file content is: <br>";
echo file_get_contents( $filename );