自动递增文件名PHP/MMySQL


Auto increment file names PHP/MySQL

我对php世界相当陌生,一直在为我的一家副业创建库存跟踪系统。大多数基本功能都可以使用,但我的"上传pdf"功能有问题。即使它能工作并将pdf文件上传到目标位置,我也无法将文件名($docid)设置为每次提交时自动递增的整数,这样文件就永远不会有相同的名称。以下是我正在工作的代码:

$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>';
                }
            }
        }

我知道我需要某种循环来自动增加$docid变量,但我似乎无法解决。我已经读过这个话题了,但if语句的自动递增让我很反感。任何帮助都将不胜感激。

干杯

好吧,除非你将条目存储在数据库或类似的数据库中,否则你可以检查上传文件夹中的条目,并将其增加一个。

glob函数在以下方面很有用: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";

正如评论中所指出的。。。我发现用时间戳生成的字符串来命名它是一个更好的主意。也不要忘记字符串周围的引号。

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

编辑

我想,最好是用一个格式化的日期来命名。

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