如何在PHP中上传.txt文件并在另一页上逐行读取? [英] How does one upload a .txt file in PHP and have it read line by line on another page?

查看:232
本文介绍了如何在PHP中上传.txt文件并在另一页上逐行读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在表单上上传一个.txt文件(浏览),将文件发布到另一个php页面,然后让这个文件逐行阅读。



我的代码到目前为止在这里。
文件1:HTML上传:

 < form action =TestParse.phpmethod =postenctype = 多部分/格式数据 > 
< label for =file>文件名:< / label> < input type =filename =fileid =file/>
< input type =submitvalue =Submit>
< / form>

文件2:读取文件

<$ p $($ _FILES [file] [error]> 0)
{
echoError:。 $ _FILES [file] [error]。 < br />;

elseif($ _FILES [file] [type]!==text / plain)
{
echo文件必须是.txt ;



$ file_handle = fopen($ _ FILES [file] [name],rb);





$ b当我看到它时,第二个文件将验证没有错误上传的文件是.txt。然后fopen()文件,然后我可以阅读与fgets()(我设法得到所有这些工作)。

然而,这代码仅在正在上传的.txt文件恰好与PHP文件位于同一目录中时才起作用。否则,我会收到很多错误消息。而当你不能上传一个不在PHP文件夹中的文件的时候,它首先会破坏文件上传系统的功能。

有人能告诉我什么这个代码有错?

解决方案

一行一行地阅读,它为我工作这个代码:

  $ fp = fopen($ _ FILES ['uploadFile'] ['tmp_name'],'rb'); ($ line = fgets($ fp))!== == false){
echo $ line< br>;
}

您无需保存。


My objective here is to upload a .txt file on a form (browse), post the file to another php page, and then have that file read line by line.

My code so far is here. FILE 1: HTML UPLOAD:

<form action="TestParse.php" method="post" enctype="multipart/form-data">
   <label for="file">Filename:</label> <input type="file" name="file" id="file"/>
<input type="submit" value="Submit">
</form>

FILE 2: READING THE FILE

    if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
elseif ($_FILES["file"]["type"] !== "text/plain")
{
echo "File must be a .txt";
}
else
{
$file_handle = fopen($_FILES["file"]["name"], "rb");
}

As I see it, the second file would verify that there is no error and that the uploaded file is a .txt. It would then fopen() the file and I would then be able to read with fgets() (I have managed to get all this to work).

However, this code only works if the .txt file that is being uploaded happens to be in the same directory as the PHP file. Otherwise I get lots of error messages. And when you cannot upload a file that's not in the PHP file's folder, it defeats the purpose of having a file upload system in the first place.

Can someone tell me what is wrong with this code?

解决方案

to read line by line, it worked for me this code:

$fp = fopen($_FILES['uploadFile']['tmp_name'], 'rb');
    while ( ($line = fgets($fp)) !== false) {
      echo "$line<br>";
    }

you do not need to save it.

这篇关于如何在PHP中上传.txt文件并在另一页上逐行读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆