35

If I upload a text file via a form, is it possible to output its contents directly from the $_FILES variable rather than saving it onto the server first? I know this is a security risk, but it will only be run on a local machine.

3 Answers 3

82

Doing

file_get_contents($_FILES['uploadedfile']['tmp_name']); 

is valid however you should also check to make sure that the file was uploaded through a form and that no errors occurred during upload:

if ($_FILES['uploadedfile']['error'] == UPLOAD_ERR_OK               //checks for errors
      && is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) { //checks that file is uploaded
  echo file_get_contents($_FILES['uploadedfile']['tmp_name']); 
}

A helpful link is https://www.php.net/manual/en/features.file-upload.php

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, why should I check file via is_uploaded_file? Is there some security issue? What problem it can cause? Can you explain it to me or provide some link to post? Thank you
58

The file is saved to temp directory the moment it's uploaded, but you can use $_FILES['uploadedfile']['tmp_name'] to read it without having to save in a permanent place.

1 Comment

Doh, I was doing this all along, but the HTML was nothing that would be visible on the page. I'm using chrome, so when I clicked view source, it showed me a re-loaded version of the page, where the text file had not been loaded:)
6

Unfortunately, no. At least not through the $_FILES variable. Sorry.

EDIT: It is always saved as the temp file in $_FILES and you'll always have to use that one for content.

3 Comments

Okay, fine, I'll just not post when I know the answer is bad news!
This answer is strictly true because the question asked specifically about the $_FILES variable but I think the other answers are correct for what the post seems to ask!
Yeah like Lukos said, you got it wrong, "Unfortunately, no" is incorrect. You can get the contents from an uploaded file without saving it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.