重命名file_upload.php中的文件

时间:2011-09-05 17:02:31

标签: php forms file-upload

就像一个白痴我同意为客户创建一个表单(我通常只做HTML和CSS编码),它包含PHP用于sendmail /文件上传。我认为在网上过多的教程并不太难,我想开始学习PHP。我在客户端处于领先地位,我没有使用过PHP的经验并且给了很大的折扣,因为我认为这是一个学习机会而不是合同工作。

我在开发过程中将表单作为两个独立的部分运行:

  1. sendmail.php
  2. file_upload.php。
  3. 所以我为自己感到骄傲。但是,我现在正在尝试重命名上传的文件,如下所示:

    ClientCompanyName_ProjectName_FileName_Increment.Extension
    

    是的,这似乎很长,但客户想要非常简单地区分单个目录中的单个文件(我不知道如何在客户端的客户端上传新文件时创建新的唯一目录)。

    正如我所说,在尝试重命名文件之前,我有file_upload.php函数。一旦我添加了代码,我想通过从FORM输入字段中提取来重命名该文件,我打破了PHP,现在已经失去了如何根据需要使其工作。

    一个简单的表格如下,我对form_input.php的php在下面。

    <form action="./upload.php" method="post" enctype="multipart/form-data">
    <label for="company">Company Name:</label><input type="text" name="company" id="company" />
    <br />
    <label for="proj_name">Project Name:</label><input type="text" name="proj_name" id="proj_name" />
    <br />
    <label for="file">Select a File:</label><input type="file" name="userfile" id="file" />
    <br />
    <input type="submit" name="submit" id="submit" value="Upload File" />
    </form>
    
    <?php
    if (isset($_POST['submit'])) {
        // Configuration - Script Options
        $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension
        $file_basename = substr($filename, 0, strripos($filename, '.')); // Get file name minus extension
        $file_ext = substr($filename, strripos($filename, '.')); // Get file extension
        $filesize = $_FILES['file']['size']; // Get file size
        $allowed_file_types =      
            array('.jpg','.jpeg','.gif','.bmp','.png','.pdf','.doc','.docx','.psd'); 
            // These will be the types of files that are allowed to 
            // pass the upload validation
        $file_counter = 1; // used to increment filename if name already exists 
        $company = $_REQUEST['company']; 
        $project = $_REQUEST['proj_name'];
    
        // File renaming and upload functionality
        if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000001)) { 
            // Checks to make sure uploaded file(s) is an allowed file 
            // type AND within the allowable file size (currently 10MB)
            // Rename File
            $newfilename = $company . '_' . $proj_name . '_' . $file_basename; 
            // Rename file as (CompanyName_FileName_DateStamp)
            // Loop until an available file name is found
            while (file_exists( "file_uploads/" . $newfilename ))
                $finalfilename = $newfilename . '_' . $file_counter++ . $file_ext; 
            // This will be the File Name shown in the upload destination directory
            // (currently the "file_uploads" directory)
            if (file_exists("file_uploads/" . $finalfilename)) {
                // file already exists error
                echo "This file already exists. Please rename this file and upload again if necessary."; 
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "file_uploads/" . $finalfilename); 
                echo "File uploaded successfully."; 
            } 
        }    elseif (empty($file_basename)) {
             // file selection error
             echo "Please select a file to upload."; 
        } elseif ($filesize > 10000000) {
            //file size error
            echo "The file you are trying to upload is too large. Files must be no larger than 10MB."; 
        } else {
            // file type error
            echo "The file you attempted to upload is not allowed. You can only upload the following types of files: .jpg, .jpeg, .gif, .bmp, .png, .pdf, .doc, .docx, and .psd."; 
            unlink($_FILES["file"]["tmp_name"]); 
        }
    }
    
    ?>
    

    当我尝试上传文件时,我收到以下错误的变体:

      

    解析错误:语法错误,第27行/home4/yourpass/public_html/upload/upload.php中的意外T_ELSE

    当我修复一个错误时,在另一行上发生新的类似错误,最后我收到一条错误,指出文件已存在但服务器上的目录中没有重复文件。

    对于那些想要尝试此表单的实时版本的人,您可以通过以下链接进行操作:

    http://www.niagarathistle.com/upload/form_upload.html

    任何帮助或推动正确的方向将不胜感激。谢谢!

    PS:很抱歉代码格式化。我仍然试图弄清楚如何轻松地使用Markdown获取我的代码并正确格式化。

2 个答案:

答案 0 :(得分:0)

您的逻辑中有错误:

    // Checks to make sure uploaded file(s) is an allowed file 
    // type AND within the allowable file size (currently 10MB)
    // Rename File
    $newfilename = $company . '_' . $proj_name . '_' . $file_basename;

    // $finalfilename will not be set, unless the while-loop is entered
    // so we just set a default one
    $finalfilename = $newfilename;

    while (file_exists( "file_uploads/" . $finalfilename ))
        $finalfilename = $newfilename . '_' . $file_counter++ . $file_ext; 

现在可行。

答案 1 :(得分:0)

我找到了一些代码未按预期工作的地方,以及一些拼写错误。以下代码适用于我的Dreamhosted网站。

我修复的具体问题:

  • $_FILES['file']的引用应该是$_FILES['userfile'](这可能是您的服务器特有的,我不确定,但您最初使用$_FILES['userfile']
  • $newfilename需要添加$file_ext
  • 添加了对move_uploaded_file()成功
  • 的检查
  • $_REQUEST超全局更改为$_POST(除非必须,否则不应使用$_REQUEST
  • 我考虑了@Lars的回答

如果您想尝试一下,请参阅:

http://jfcoder.com/test/fileupload.php

如果您想查看背后的代码,请使用以下链接:

http://jfcoder.com/test/fileupload.php?show=true

另外,我可能建议使用库/框架/ CMS而不是滚动自己的代码(如果你是设计师,我会看CodeIgniter / ExpressionEngine)。< / p>

<?php
if (isset($_POST['submit'])) {
    // Configuration - Script Options
    $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension
    $file_basename = substr($filename, 0, strripos($filename, '.')); // Get file name minus extension
    $file_ext = substr($filename, strripos($filename, '.')); // Get file extension
    $filesize = $_FILES['userfile']['size']; // Get file size
    $allowed_file_types =      
        array('.jpg','.jpeg','.gif','.bmp','.png','.pdf','.doc','.docx','.psd'); 
        // These will be the types of files that are allowed to 
        // pass the upload validation
    $file_counter = 1; // used to increment filename if name already exists 
    $company = $_POST['company']; 
    $project = $_POST['proj_name'];

    // File renaming and upload functionality
    if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000001)) { 
        // Checks to make sure uploaded file(s) is an allowed file 
        // type AND within the allowable file size (currently 10MB)
        // Rename File
        $newfilename = $company . '_' . $project . '_' . $file_basename . $file_ext;

        // $finalfilename will not be set, unless the while-loop is entered
        // so we just set a default one
        $finalfilename = $newfilename;

        while (file_exists( "file_uploads/" . $finalfilename ))
            $finalfilename = $newfilename . '_' . $file_counter++ . $file_ext;

        // This will be the File Name shown in the upload destination directory
        // (currently the "file_uploads" directory)
        if (file_exists("file_uploads/" . $finalfilename)) {
            // file already exists error
            echo "This file already exists. Please rename this file and upload again if necessary."; 
        } else {
            if (move_uploaded_file($_FILES["userfile"]["tmp_name"], "file_uploads/" . $finalfilename)) {
                echo "File uploaded successfully.";
                echo " <a href=\"/test/file_uploads/$finalfilename\">Link</a>";
            } else {
                echo "File not uploaded/moved successfully. ";
            } 
        } 
    }    elseif (empty($file_basename)) {
         // file selection error
         echo "Please select a file to upload."; 
    } elseif ($filesize > 10000000) {
        //file size error
        echo "The file you are trying to upload is too large. Files must be no larger than 10MB."; 
    } else {
        // file type error
        echo "The file you attempted to upload is not allowed. You can only upload the following types of files: .jpg, .jpeg, .gif, .bmp, .png, .pdf, .doc, .docx, and .psd."; 
        unlink($_FILES["userfile"]["tmp_name"]); 
    }
}

?>