开发者

Rename files in file_upload.php

Like an idiot I agreed to create a form for a client (I typically just do HTML and CSS coding) that incorporates PHP for a sendmail/file upload. I didn't think it would be too difficult with the plet开发者_StackOverflow中文版hora of tutorials online and I wanted to begin learning PHP anyways. I was upfront with the client that I have no experience with PHP and gave a significant discount as I look at this as a learning opportunity more than contract work.

I have the form functioning as 2 separate parts during development:

  1. the sendmail.php
  2. the file_upload.php.

So I'm quite proud of myself. However, I am now trying to rename uploaded files as follows:

ClientCompanyName_ProjectName_FileName_Increment.Extension

Yes, this seems long but client wants VERY SIMPLE way of differentiating individual files in a single directory (i don't know how to create new unique directories when client's clients upload new files).

As I said, I had the file_upload.php function working prior to trying to rename the files. Once I added code that I THOUGHT would rename the file by pulling from FORM input fields, I broke the PHP and am now lost as to how to get it to work as needed.

A simple form is as follows, and the php I have for form_input.php is below.

<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"]); 
    }
}

?>

When I try to upload a file now I am getting variations of the following error:

Parse error: syntax error, unexpected T_ELSE in /home4/yourpass/public_html/upload/upload.php on line 27

When I fix one error, a new similar error occurs on a different line, and finally I get an error that states File already exists but there is no duplicate file in the directory on the server.

For those of you who would like to try a live version of this form you can do so at this link:

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

Any help or a nudge in the right direction would be appreciated. Thanks!

PS: Sorry for the code formatting. I'm still trying to figure out how to EASILY get my code in and formatted properly using Markdown.


You have an error in your logic:

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

Now it works.


I found a few spots where your code wasn't working as expected, and a few typos. The below code works on my Dreamhosted site.

Specific issues that I fixed:

  • References to $_FILES['file'] should have been $_FILES['userfile'] (this may be specific to your server, I'm not sure, but you initially use $_FILES['userfile'])
  • $newfilename needed the $file_ext added to it
  • Added a check for move_uploaded_file() success
  • Changed $_REQUEST superglobal to $_POST (you should not use $_REQUEST unless you have to)
  • I took into account @Lars' answer

If you would like to try it out, see:

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

If you would like to see the code behind, use the following link:

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

Also, I'd probably recommend using a library/framework/CMS instead of rolling your own code (if you're a designer, I'd look at CodeIgniter/ExpressionEngine).

<?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"]); 
    }
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜