生成没有数据库的顺序发票号

问题描述 投票:1回答:2

我正在用PHP创建发票,而发票编号我想生成一个序号。

我正在使用gettimeofday()来生成发票号,但这给了我一个非序列号,看起来像这样:46023913

<?php 
$new_invoice = gettimeofday(); 
$new_invoice = $new_invoice[sec]; 
$new_invoice = $new_invoice - 1509000000;
echo $new_invoice;
?>
php
2个回答
1
投票

创建一个带有数字的文本文件'counter.txt'(1509000000)用file_get_contents(counter.txt)读取文件然后更新文件

我有一段时间没有在PHP工作,但它有点像

根据KIKO:锁定文件

<?php

$num = file_get_contents('counter.txt');

echo $num;
$handle = fopen('counter.txt','w+');

if (flock($handle,LOCK_EX)){

  $num++;
  fwrite($handle,$num);
  fclose($handle);
  // release lock
  flock($handle,LOCK_UN);
} else {
  echo "Error locking file!";
}

$num = file_get_contents('counter.txt');

echo $num;

类似的东西。


1
投票

Richardwhitney现在已经包含了文件锁,但它做得并不好。如果锁已经存在,他的代码将产生错误。那不是实际的。下面的代码将等待最多10秒钟才能解锁文件。

// open the file
$handle = fopen("counter.txt","r+");
if ($handle) {
    // place an exclusive lock on the file, wait for a maximum of 10 seconds
    $tenths = 0;
    while (!flock($handle, LOCK_EX)) {
        $tenths++;
        if ($tenths == 100) die('Could not get a file lock.');
        usleep(100000);
    }
    // get old invoice number
    $oldInvoiceNo = fgets($handle);
    // create a new sequential invoice number
    $newInvoiceNo = $oldInvoiceNo++;
    // write the new invoice number to the file
    ftruncate($handle, 0);
    fwrite($handle, $newInvoiceNo);
    // unlock the file
    flock($handle, LOCK_UN);
    // close the file
    fclose($handle);
}
else die('Could not open file for reading and writing.');

锁定文件时,请尽量在尽可能短的时间内完成此操作。

最好将此代码与其余代码隔离,例如在函数中。

function getNewInvoiceNo($pathToCounter)
{
    // open the file
    $handle = fopen($pathToCounter, "r+");
    if ($handle) {
        // place an exclusive lock on the file, wait for a maximum of 10 seconds
        $tenths = 0;
        while (!flock($handle, LOCK_EX)) {
            $tenths++;
            if ($tenths == 100) die('Could not get a file lock.');
            usleep(100000);
        }
        // create a new sequential invoice number
        $newInvoiceNo = fgets($handle) + 1;
        // write the new invoice number to the file
        ftruncate($handle, 0);
        fwrite($handle, $newInvoiceNo);
        // unlock the file
        flock($handle, LOCK_UN);
        // close the file
        fclose($handle);
    }
    else die('Could not open file for reading and writing.');
}
© www.soinside.com 2019 - 2024. All rights reserved.