标题很清楚:
我有一个PHP文件,我希望它只在第一次执行,即使有100.000个用户试图同时访问它。
发布于 2012-11-15 08:20:44
您可以使用写入服务器的锁定文件来完成此操作,如下所示:
if (!is_file("visited_once.txt"))
{
//you're the one
file_put_contents("visited_once.txt", "");
}但也许数据库解决方案会更复杂,因为我不能100%确定文件解决方案是否适用于100.000个并发请求。
创建表
CREATE TABLE visited
(
visit int NOT NULL,
UNIQUE (visit)
);在请求时执行以下操作
try
{
$db->query("INSERT INTO visited VALUES (0)");
//you're the one
}
catch (Exception $ex)
{
//nope! Already visited
}这使用唯一的键并依赖于数据库的一致性。
发布于 2012-11-15 08:18:21
<?php
if(file_exists('check.txt')) exit;
file_put_contents('check.txt','1');
...your code...
?>发布于 2012-11-15 08:18:43
我会向文件中写入一些内容,作为脚本正在执行的标志,并在脚本的末尾删除该文件。在脚本开始时,检查文件是否存在。
例如:
$flag_file = 'flag.tmp';
if (file_exists($flag_file)) exit();
file_put_contents($flag_file, 1);
// rest of the script
unlink($flag_file);https://stackoverflow.com/questions/13389632
复制相似问题