Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get content of file uploaded by user before saving [closed]

See, I provide the users of my website the possibility of upload their own PHP/HTML/TXT files into my server, right?... But I want to get that file content without saving it in my server and save the content into a string, or whatever.

It is possible to do that?... If not, what should I do to get the content after saving the file in my server?... please, help me!

I don't know if this can help, but this is the code I use to upload the user files.

$allowedExts = array("php", "html", "txt");
$tmp = explode(".", $_FILES["file"]["name"]);
$extension = end($tmp);

if 
((($_FILES["file"]["type"] == "application/octet-stream") 
|| ($_FILES["file"]["type"] == "text/php") 
|| ($_FILES["file"]["type"] == "text/html") 
|| ($_FILES["file"]["type"] == "text/plain")) 
&& ($_FILES["file"]["size"] < 50000) && in_array($extension, $allowedExts))
{
    if ($_FILES["file"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
}
else
{
    echo "Invalid file";
}
like image 812
Jerome Avatar asked Jun 03 '13 00:06

Jerome


1 Answers

Use file_get_contents() for that:

echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];

// store file content as a string in $str
$str = file_get_contents($_FILES["file"]["tmp_name"]);

Note that if you need the file for later usage too then you'll have to copy it to a destination location additionally. Like this:

 move_uploaded_file($_FILES["file"]["tmp_name"], 'contents/' . $_FILE['name']);
like image 189
hek2mgl Avatar answered Nov 13 '22 23:11

hek2mgl