Sunday, March 20, 2011

PHP $_FILES['tmp_name']

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

From stackoverflow
  • $_FILES["file"]["name"] - the name of the uploaded file

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

    Jaspero : If I use $_FILES["file"]["name"] and assign it to a variable, say $attachment, than it will not work because, that returns just a file name. I think I'll need to give the path and path can come only from tmp_name. Please correct me if I am wrong.
    Marc B : Most mail libraries have two filenames you use for attachments. One is the name/location of the file on the server, the other is the name as you want the user to see it. In your case, the name/location is `tmp_name`, and the end-user filename is `name`.
    Gabi Purcaru : From your question I understand that you want to store the file on the server, by using the name instead of tmp_name. The thing to do is use http://php.net/manual/en/function.move-uploaded-file.php `move_uploaded_file()` and move the `tmp_file` to its permanent path with `name` filename.
    Jaspero : No, I want to send the file in an email not upload to server.
    Gabi Purcaru : Then, you can `rename($_FILES["file"]["tmp_name"], $_FILES["file"]["name"])` it...
  • $_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.

    Jaspero : $geekMail->attach('/home/willem/file2.zip') should be the format to use the library. So I had to use $attachment = $_FILES['file']['tmp_name']; $geekMail->attach($attachment); Is there a way I can pass ['name'] as well along with the path?
  • 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);
    

0 comments:

Post a Comment