创建文件上传表单,上传文本文件,读取文本文件内容,在控制台输出,并修改文件内容。创建文件上传表单,上传文本文件,读取文本文件内容,在控制台输出,并修改文件内容。
要求:创建文件上传表单,上传文本文件;读取文本文件内容,在控制台输出;修改文件内容。修改文件内容。
这是一个包含文件上传、读取和修改的PHP示例。首先,我们需要创建一个HTML表单来上传文件:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select text file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
然后,我们需要创建一个PHP脚本(命名为"upload.php")来处理文件上传,读取文件内容并修改它:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file is a text file
if($fileType != "txt") {
echo "Sorry, only TXT files are allowed.";
exit;
}
// Attempt to upload file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Read and output the file contents
$fileContents = file_get_contents($target_file);
echo "File contents: " . $fileContents;
// Modify the file contents
$fileContents = str_replace('old text', 'new text', $fileContents);
file_put_contents($target_file, $fileContents);
echo "File contents have been modified.";
?>
这个PHP脚本首先检查上传的文件是否为文本文件,然后尝试将文件移动到"uploads/"目录。如果文件上传成功,它将读取文件内容并输出,然后替换文件内容中的"old text"为"new text"。
请注意,你需要确保PHP有足够的权限来写入"uploads/"目录。你也可能需要根据你的需求来修改这个脚本。
不知道你这个问题是否已经解决, 如果还没有解决的话:写的不好,欢迎吐槽,手动微笑 :)!
/**
* Created by PhpStorm.
* User: zhanghengyu
* Date: 2016/9/2
* Time: 18:17
*/
namespace File;
class FileOperate
{
//写入文件
public function writeToHeadHandle($username, $content)
{
$filePoint = fopen('data.txt', 'w');
if ($filePoint) {
fwrite($filePoint, $username."\r\n");
fwrite($filePoint, $content."\r\n");
} else {
echo '打开文件错误';
}
fclose($filePoint);
}
//追加内容到文件尾部
public function writeToEndHandle($username, $content)
{
$filePoint = fopen('data.txt', 'a');
if ($filePoint) {
fwrite($filePoint, $username."\r\n");
fwrite($filePoint, $content."\r\n");
} else {
echo '打开文件错误';
}
fclose($filePoint);
}
//读取文件
public function readHandle()
{
$filePoint = fopen('data.txt', 'r');
if ($filePoint) {
while (($buffer = fgets($filePoint, 4096)) != NULL) {
echo $buffer.'';
}
} else {
echo '打开文件错误';
}
fclose($filePoint);
}
}
$fileOperateObj = new FileOperate();
$fileOperateObj->writeHandle('张全蛋','我是掘球莱火雷蛋');
$fileOperateObj->readHandle();
效果图:
data.txt
好了,这次常见的文件操作就介绍到这里,后面我会基于本次博文实现一个异步的留言板。