forked from Viper-7/Snippets
/
sequence.php
47 lines (37 loc) · 1.41 KB
/
sequence.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
echo getSequence('test', '/temp');
function getSequence($name, $folder = '/tmp', $default = 0)
{
// Build a filename from the folder and sequence name
$filename = realpath($folder) . '/' . $name . '.seq';
// Open the file
$fp = fopen($filename, "a+");
// Lock the file so no other processes can use it
if (flock($fp, LOCK_EX)) {
// Fetch the current number from the file
$num = trim(stream_get_contents($fp));
// Check that what we read from the file was a number
if(!ctype_digit($num))
{
// If its not a number, lets reset to the default value
$newnum = $default;
} else {
// If its a number, increment it
$newnum = $num + 1;
}
// Delete the contents of the file
ftruncate($fp,0);
rewind($fp);
// Write the new number to the file
fwrite($fp, "{$newnum}\n");
// Release the lock
flock($fp, LOCK_UN);
} else {
echo "Couldn't get the lock!";
}
// Close the file
fclose($fp);
// Return the incremented number
return $newnum;
}
?>