Solved

php upload file with name and not tmp_name

Posted on 2015-01-22
2
329 Views
Last Modified: 2015-02-07
Hi,

In cakephp I can send an email with an attachment and it  works fine.

My issue is the attachment takes the name of the tmp_name so the user recieving thr=e email attachment will have an odd filename.

How do I change the name of the tmp_name attachment? I tried rename *doesnr work and I tried move_upload which i dont want to upload and store the file so thats no good.

This is a php issue.
    echo $this->Form->input('file', array('type' => 'file'));
		echo "<BR/>";
                
        echo $this->Form->input('message', array('label' => 'Message' ));  
 
        echo $this->Form->submit('Send', array('name'=>'send'));
        
        echo $this->Form->end(); ?>

Open in new window

         $data=$this->request->data;
              $tmp=$data['Myemail']['file']['tmp_name']; //tmp_name of file after uploaded
              $tmp2=$data['Myemail']['file']['name'];  //name of uploaded file 
               
               
              rename($tmp, $tmp2); //doesnt work
          
            
                $message=$data['Myemail']['message'];
                 $Email = new CakeEmail();
                             $Email->config('gmail2');  
                          
                             $to='jagguy999@gmail.com';
                             $Email->from( array('jagguy999@gmail.com' => 'Aptutoring'));
                             $Email->to($to);
                             $Email->subject('Hello');
                       
                             $Email->attachments($tmp); //I want the attachment name and not the tmp_name
                        
                        $Email->send($message);  

Open in new window

0
Comment
Question by:jagguy
  • 2
2 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40565645
I think Cake may be getting in the way of how PHP works under the covers.  Here is what PHP does and how to use it correctly.

When your client uploads a file with <input type="file"> PHP presents the script with an array named $_FILES.  The $_FILES array tells you whether the upload worked (and maybe why it failed, if it did) as well as the basename of the file on the client computer, and the temporary name of the file on your server.  After the upload completes, your server-side script is responsible for moving the temporary file into a permanent storage location, because PHP will delete the temporary storage at the end of the script.  The temporary storage is just for the convenience of PHP, and cannot be relied upon, except as described in the PHP documentation.  Basically, your script has the obligation to (1) determine if the upload worked, (2) gather any information you need from $_FILES, (3) move the file from the temporary storage to a permanent location on your server, (4) tell the client if the upload worked and where your script has stored the file.

Here are the relevant man pages.  Please read these over and post back if you're still stuck on anything.

http://php.net/manual/en/features.file-upload.php
http://php.net/manual/en/features.file-upload.common-pitfalls.php
http://php.net/manual/en/function.move-uploaded-file.php
http://php.net/manual/en/reserved.variables.files.php

If you're dealing with large files...
http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
http://php.net/manual/en/ini.core.php#ini.post-max-size
http://php.net/manual/en/info.configuration.php#ini.max-input-time

HTH, ~Ray
0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40565647
Not a Cake example, but this shows all of the moving parts of the file-upload process.  Cake undoubtedly implements many parts of this process.  Once you understand the process, you'll also be able to understand what the Cake framework is doing for you and what parts you must do yourself.

<?php // demo/upload_one_file.php
error_reporting(E_ALL);

/**
 * Upload and store a file
 */
 
// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT (USE UPPERCASE ONLY)
$file_exts = array
( 'XLS'
, 'XLSX'
, 'PDF'
, 'CSV'
)
;
$f_exts = implode(', ', $file_exts);

// ESTABLISH THE NAME OF THE DESTINATION FOLDER
$my_dir = getcwd();

// OR USE THIS TO PUT UPLOADS IN A SEPARATE FOLDER
$my_dir = 'storage';
if (!is_dir($my_dir))
{
    mkdir($my_dir);
}

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;


// IF THERE IS INFORMATION POSTED
if (!empty($_POST))
{
    // IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code)
    {
        trigger_error($errors[$error_code], E_USER_ERROR);
    }

    // GET THE FILE SIZE
    $fsize = number_format($_FILES["userfile"]["size"]);

    // SYNTHESIZE THE NEW FILE NAME FOR TEMPORARY STORAGE
    $fname = basename($_FILES['userfile']['name']);

    // FAIL IF THIS IS NOT AN ALLOWABLE EXTENSION
    $f_ext = explode('.', $fname);
    $f_ext = end($f_ext);
    $f_ext = strtoupper(trim($f_ext));
    if (!in_array($f_ext, $file_exts)) trigger_error("$f_ext NOT ALLOWED.  CHOOSE FROM $f_exts", E_USER_ERROR);

    // THE SERVER PATH TO THE FILE
    $my_path
    = getcwd()
    . DIRECTORY_SEPARATOR
    . $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // THE URL PATH TO THE FILE
    $my_url
    = $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // MESSAGES ABOUT THE UPLOAD STATUS, IF ANY
    $msg = NULL;

    // IF THE FILE IS NEW (DOES NOT EXIST)
    if (!file_exists($my_path))
    {
        // IF THE MOVE FUNCTION WORKED CORRECTLY
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
        {
            $upload_success = 1;
        }
        // IF THE MOVE FUNCTION FAILED IT PROBABLY THREW A MESSAGE
        else
        {
            $upload_success = -1;
            trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
        }
    }

    // IF THE FILE ALREADY EXISTS
    else
    {
        $msg .= "<br/><b><i>$my_url</i></b> already exists" . PHP_EOL;

        // SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($_POST["overwrite"]))
        {
            $upload_success = 0;
        }

        // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        else
        {
            $now    = date('Y-m-d-His');
            $my_bak = $my_path . '.' . $now . '.bak';
            if (!copy($my_path, $my_bak))
            {
                $msg .= "<br/><strong>Attempted Backup Failed!</strong>" . PHP_EOL;
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
            {
                $upload_success = 2;
            }
            else
            {
                $upload_success = -1;
                trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
            }
        }
    }

    // PREPARE A REPORT OF THE SCRIPT'S SUCCESS OR FAILURE
    if ($upload_success == 2) { $msg .= "<br/>A backup was made and the file was overwritten" . PHP_EOL; }
    if ($upload_success == 1) { $msg .= "<br/><strong>$my_url</strong> has been saved" . PHP_EOL; }
    if ($upload_success == 0) { $msg .= "<br/><strong>It was NOT overwritten.</strong>" . PHP_EOL; }
    if ($upload_success < 0)  { $msg .= "<br/><strong>ERROR: $my_url NOT SAVED - SEE WARNING FROM move_uploaded_file()</strong>" . PHP_EOL; }

    // ADD FILE SIZE AND PERMISSION INFORMATION
    if ($upload_success > 0)
    {
        $msg .= "<br/>$fsize bytes uploaded" . PHP_EOL;
        if (!chmod ($my_path, 0755))
        {
            $msg .= "<br/>chmod(0755) FAILED: fileperms() = ";
            $msg .= substr(sprintf('%o', fileperms($my_path)), -4);
        }
    }

    // SHOW THE SUCCESS OR FAILURE
    echo $msg;

    // SHOW A LINK TO THE FILE
    echo '<br/>'
    . '<a href="'
    . $my_url
    . '" target="_blank">'
    . "See: $my_url"
    . '</a>'
    ;
}


// CREATE THE FORM FOR INPUT (USING HEREDOC SYNTAX)
$form = <<<ENDFORM
<p>Upload one file
<form enctype="multipart/form-data" method="post">
<!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
Find a file to Upload ($f_exts): <input name="userfile" type="file" />
<br/>Check this box
<input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files
</br><input type="submit" value="Upload" />
</form>
</p>
ENDFORM;

echo $form;

Open in new window

0

Featured Post

Connect further...control easier

With the ATEN CE624, you can now enjoy a high-quality visual experience powered by HDBaseT technology and the convenience of a single Cat6 cable to transmit uncompressed video with zero latency and multi-streaming for dual-view applications where remote access is required.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you are a web developer, you would be aware of the <iframe> tag in HTML. The <iframe> stands for inline frame and is used to embed another document within the current HTML document. The embedded document could be even another website.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question