How can I create a variable from a text file that a user uploads? I don't want the text file permanately saved on the server, I just need to get the contents on the file into a variable, process it and then display a result. Anyone know how to do this?
Form code: <form action="?" method="post"> <input type="file" name="datafile" /> <input type="submit" value="Submit" /> </form> Code (markup): PHP code: if (isset($_POST)) { $contents = file_get_contents($_FILES['datafile']['tmp_name']); } PHP:
Does anyone know how I can check the extension of the tmp_name file? I want to restrict the form to txt files only. I think it might have to be done before the file gets to the php tmp directory - because once it's in there it's just a random name without an extension.
Can I ask what was the problem? (just curious) Anyway, here is the code to get the file extension: preg_match('/\.([^.]+)$/', $_FILES['datafile']['tmp_name'], $m); $extension = $m[1]; PHP:
Thanks, all working now I just needed to add this to the form: enctype="multipart/form-data" Code (markup): One final question - where exactly are these tmp files stored on the server?
Okay, I always forget that! (And still didn't think of it when looking back at the code either) In a directory for temporary files, e.g. /tmp. You can force it to delete the files just after using them if you want: if (isset($_POST)) { if (is_uploaded_file($_FILES['datafile']['tmp_name'])) { $contents = file_get_contents($_FILES['datafile']['tmp_name']); @unlink($_FILES['datafile']['tmp_name']); } } PHP: Note the is_uploaded_file check, I forgot it last time, it adds a bit of security.
OK... I've looked in the tmp directory above my public_html dir on my cPanel shared hosting and there's only my webstats in there. So I did a php readdir of mydomain.com/tmp/ and got a list of session files and other junk - but none of the test txt files I've been using. Do I need to worry about deleting the uploaded tmp files? I don't even know where they are! Does everyone on a shared server share a global php tmp directory? I'm confused
Yes, they delete when the PHP script has finished executing. If you must prove this, use sleep(10); in your PHP and refresh the /tmp/ dir during this time