[php] PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

I am trying to upload a doc file from a form and send it to email. I am using

$_FILES['file']['tmp_name'];

The problem is, it is returning a randomly generated file name. So, when it reaches the inbox, the filename is phpvwRGKN.dat (filename is random each time).

How can I preserve the filename and extension?

Note: I am using geekMail class

This question is related to php

The answer is


$_FILES['file']['tmp_name']; will contain the temporary file name of the file on the server. This is just a placeholder on your server until you process the file

$_FILES['file']['name']; contains the original name of the uploaded file from the user's computer.


Just a suggestion, but you might try the Pear Mail_Mime class instead.

http://pear.php.net/package/Mail_Mime/docs

Otherwise you can use a bit of code. Gabi Purcaru method of using rename() won't work the way it's written. See this post http://us3.php.net/manual/en/function.rename.php#97347 . You'll need something like this:

$dir = dirname($_FILES["file"]["tmp_name"]);
$destination = $dir . DIRECTORY_SEPARATOR . $_FILES["file"]["name"];
rename($_FILES["file"]["tmp_name"], $destination);
$geekMail->attach($destination);

Like @Gabi Purcaru mentions above, the proper way to rename and move the file is to use move_uploaded_file(). It performs some safety checks to prevent security vulnerabilities and other exploits. You'll need to sanitize the value of $_FILES['file']['name'] if you want to use it or an extension derived from it. Use pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) to safely get the extension.


$_FILES["file"]["name"] - the name of the uploaded file

from http://www.w3schools.com/php/php_file_upload.asp


$_FILES["file"]["tmp_name"] contains the actual copy of your file content on the server while
$_FILES["file"]["name"] contains the name of the file which you have uploaded from the client computer.


If you wanna get the uploaded file name, use $_FILES["file"]["name"]

But If you wanna read the uploaded file you should use $_FILES["file"]["tmp_name"], because tmp_name is a temporary copy of your uploaded file and it's easier than using

$_FILES["file"]["name"] // This name includes a file path, which makes file read process more complex