简体   繁体   中英

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

$_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.

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

来自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.

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.

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM