我有充分的理由相信函数rename()和unlink()都是异步的,根据我的理解,这意味着当调用函数时,它们下面的代码在文件系统上完成其过程之前会继续执行。对于互联网应用程序,这是一个问题,我将在下面解释,因为以后的代码取决于这些更改,这些更改已经确定。那么,有没有办法使两者同步,以便代码读取器在遇到这些功能时冻结,直到其所有任务在文件系统上完全执行为止?
这是delete-image.php中的代码,由ajax从另一个admin-images.php调用(后者将不会显示):
`
foreach ($dirScan as $key => $value) {
$fileParts = explode('.', $dirScan[$key]);
if (isset($fileParts[1])) {
if ((!($fileParts[1] == "gif") && !($fileParts[1] == "jpg")) && (!($fileParts[1] == "png") && !($fileParts[1] == "jpg"))) {
unset($dirScan[$key]);
}
} else {
unset($dirScan[$key]);
}
}
$dirScan = array_values($dirScan);
// for thumbnail
$file = 'galleries/' . $currentGal . '/' . $currentDir . "/" . $dirScan[$imageNum - 1];
unlink($file);
for ($i = ($imageNum - 1) + 1; $i < count($dirScan); $i++) {
$thisFile = 'galleries/' . $currentGal . '/' . $currentDir . '/' . $dirScan[$i];
$thisSplitFileName = explode('.', $dirScan[$i]);
$newName = 'galleries/' . $currentGal . '/' . $currentDir . "/" . ($thisSplitFileName[0] - 1) . "." . $thisSplitFileName[1];
rename($thisFile, $newName);
}
// for large image
$fileParts = explode('.', $dirScan[$imageNum - 1]);
$file = 'galleries/' . $currentGal . '/' . $currentDir . "/large/" . $fileParts[0] . "Large." . $fileParts[1];
unlink($file);
for ($i = ($imageNum - 1) + 1; $i < count($dirScan); $i++) {
$thisSplitFileName = explode('.', $dirScan[$i]);
$thisFile = 'galleries/' . $currentGal . '/' . $currentDir . '/large/' . $thisSplitFileName[0] . "Large." . $thisSplitFileName[1];
$newName = 'galleries/' . $currentGal . '/' . $currentDir . "/large/" . ($thisSplitFileName[0] - 1) . "Large." . $thisSplitFileName[1];
rename($thisFile, $newName);
}
sleep(1);
echo 'deleted ' . $dirScan[$imageNum - 1] . " successfully!";
} else {
echo "please set the post data";
} ?>`
该脚本返回其完成的文本后,admin-
images.php触发一个新函数,该函数从这些重命名和修剪的文件中填充图像表。有时,它会显示应该删除的旧名称和文件,并且通过简单的页面刷新就可以摆脱它们。这似乎表明上述php脚本正在运行所有代码,并在完成文件系统操作之前将回显的文本吐出到mainfile中(所有其他代码又长又复杂,希望手头的讨论没有必要。
)。
您会注意到,我已经尝试过sleep()函数来停止php脚本,以期给它一些时间来完成。这是一种笨拙且有问题的处理方式,因为我必须投入大量时间来确保每次都能正常工作,但是我不希望用户等待的时间比她/他的要长。