Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php FILE POST upload without save

Tags:

I am using a plain text file in a PhP script. Is there any way to process the file in the PhP script without saving it locally? Everywhere I see simply uploading a file and saving it. I just need to pull some names off of the file and be done with it. I have everything else working if I use a local copy of the file, so saving it, then deleting it works. I was just wondering if there was a way to skip the saving a copy and just getting that information directly.

We upload the file here.

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

and in the script working with a copy of the file saved locally, I simply use

$file = fopen($_FILES['file']['name'], "r");
like image 785
anijam Avatar asked Feb 01 '12 18:02

anijam


2 Answers

If its text file (assuming size is not that huge) usually you could read it by

$contents= file_get_contents($_FILES['file']['tmp_name']);

If you are not sure which type of upload it was, check the request method

if(strtolower($_SERVER['REQUEST_METHOD'])=='post')
    $contents= file_get_contents($_FILES['file']['tmp_name']);
elseif(strtolower($_SERVER['REQUEST_METHOD'])=='put')
    $contents= file_get_contents("php://input");
else
    $contents="";
like image 99
Shiplu Mokaddim Avatar answered Sep 21 '22 19:09

Shiplu Mokaddim


When the form is submitted, check the $_FILES['input_name']['tmp_name'] property. This is the path to your file saved in a temporary /tmp system path. You can proceed reading the name using, say, file_get_contents() and then simply forget the file. System will take care of removing it.


Just to stand out of the other answers, you could theoretically read the file without even uploading it using JavaScript, see http://www.html5rocks.com/en/tutorials/file/dndfiles/. Then submit only the data you need as part of AJAX request.

like image 37
Gajus Avatar answered Sep 22 '22 19:09

Gajus