Search code examples
phpmysqlinventory

Auto increment file names PHP/MySQL


I am fairly new to the php world and have been creating an inventory tracking system for one of my side businesses. Most of the basics are working, but I am having issues with my "upload pdf" function. Even though it works and uploads the pdf file to its target location, I cannot get the file name ($docid) to be an integer that auto increments every time there is a submission so that files never have the same name. Below is the code I have working:

$pdfPath = "/Documents/TEST/";

$maxSize = 102400000000;

$docid = TEST;

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_pdf'])) { 
        if (is_uploaded_file($_FILES['filepdf']['tmp_name'])) {
            if ($_FILES['filepdf']['type'] != "application/pdf") {
                echo '<p>The file is not in PDF</p>';
            } else if ($_FILES['filepdf']['size'] > $maxSize) {
                echo '<p class="error">File is too big! Max size is =' . $maxSize . 'KB</p>';
            } else {
                $menuName = "Order_Receipt_".$docid.".pdf";
                $result = move_uploaded_file($_FILES['filepdf']['tmp_name'], $pdfPath . $menuName);
                if ($result == 1) {                 
                    echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=http://localhost/website/enter_new_order_success.html">';

                } else {
                    echo '<p class="error">Error</p>';
                }
            }
        }

I know I need some sort of loop to auto increment that $docid variable but I cannot seem to figure it out. I have read up on the topic, but auto increment with the if statement is throwing me off. Any help would be greatly appreciated.

Cheers


Solution

  • Well, unless you store the entries to keep track in a database or similar you could check what entries you have in your upload folder and increment it by one.

    The glob function is useful for that: http://php.net/manual/en/function.glob.php

    $myFiles = sort(glob('/Documents/TEST/*.pdf')); // returns an array of pdf files in the target folder. Using sort to sort the array e.g. file_1_.pdf,file_2_.pdf,file_3_.pdf, etc
    
    //last element
    $lastFile = end($myFiles);  //returns the last file in the array
    
    //get the number and increment it by one
    $number = explode('_',$lastFile);
    $newNumber = $number[1] + 1; //add this to the name of your uploaded php file.
    
    $pdfUploadedFile= "Order_Receipt_".$newNumber."_.pdf";
    

    As pointed out in the comments... I find it a better idea to name it with a timestamp generated string. And also don't forget the quotes around your strings.

    $docid = TEST;
    
    should be:
    
    $docid = 'TEST';
    

    Edit

    Even better would be naming it in a formatted date I suppose.

    $pdfUploadedFile= "Order_Receipt_".date("Y-m-d-H-i-s").".pdf"; // will output something like Order_receipt_2014-09-24-11-14-44.pdf