Ali
Ali

Reputation: 267287

Get the contents of an uploaded file without storing it

Say the user uploads a text file using PHP on my website. I want to get just the contents of this text file, and then process them, without having to store the file/do move_uploded_file() anywhere on the disk, so I won't have to deal with deleting it when I'm done with it, etc.

Is there a way to get the file's contents using the tmp_name or any other info?

Upvotes: 2

Views: 4145

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

You can retrieve information related to uploaded file using $_FILES Super global array.

$_FILES['input-field-name']['tmp_name'] will store the name of temporary copy of uploaded file on the server

So you can retrieve the contents of uploaded file using file_get_contents() function through passing value of $_FILES['input-field-name']['tmp_name'] as arguement .

The temporary copy is removed after script execution is terminated.

Please refer the example code snippet mentioned below.

<?php if($_SERVER['REQUEST_METHOD']=='POST')
      {
         if(isset($_FILES['input-field-name']))
         {

         $file_content=file_get_contents($_FILES['input-field-name']['tmp_name']);
         }
      }
  ?>

Upvotes: 5

MyStream
MyStream

Reputation: 2553

In this instance:

file_get_contents() on the tmp_name part of $_POST['filename']['tmp_name'] might suffice.

Assuming your file's input name attribute has a value of 'filename'.

Upvotes: 3

Related Questions