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?
Use $_FILES["file"]["tmp_name"]
instead. And get the contents of the file with
$contents = file_get_contents($_FILES['file']['tmp_name']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With