Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one upload a .txt file in PHP and have it read line by line on another page?

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?

like image 305
user1409008 Avatar asked May 21 '12 23:05

user1409008


Video Answer


1 Answers

Use $_FILES["file"]["tmp_name"] instead. And get the contents of the file with

$contents = file_get_contents($_FILES['file']['tmp_name']);
like image 196
flowfree Avatar answered Sep 25 '22 11:09

flowfree