防止代码或函数多次执行
有没有办法防止代码块或代码中的函数多次运行,即使我重新执行(或重新加载)PHP 文件?
我的意思是,我可以限制某人多次执行 php 脚本吗?我似乎找不到方法来做到这一点。
Is there a way to prevent a code-block or a function within a code from running more than once even if I re-execute (or reload) the PHP file?
I mean, can I restrict someone from executing a php script more than once? I can't seem to find the way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您可以使用 $_SESSION 变量来确定代码是否已执行。会话变量将被设置,直到用户关闭浏览器。如果您想进一步扩展它,您可以设置一个 cookie。请参阅以下链接了解更多详细信息。
会话变量
Cookie
Yes, you can use a $_SESSION variable to determine if the code has been executed. The session variable will be set until the user closes their browser. If you want to extend it further than that, you can set a cookie. Please see the following links for more details.
Session Variables
Cookies
如果您正在使用会话,那么您可以在代码执行后在用户的会话数组中设置一个标志:
您还应该检查 sesison 变量以查看之前是否已执行过该任务。这假设用户可以接受会话 cookie。
If you are using sessions, then you can set a flag in the user's session array after the code has executed:
You should also check the sesison variable to see if the task has been executed previously. This assumes that the user can accept a session cookie.
我有一个应用程序可以做到这一点。
我们所做的是在数据库中创建一个名为 version 的表,并在其中存储版本号。当脚本运行时,它会将数据库中的版本号与 php 脚本中的版本号进行比较。并执行任何需要的操作将其“升级”到新版本,然后更新数据库中的版本号。
当然,如果版本表不存在,代码将创建它并将其标记为存储版本零。
I have an app that does that.
What we did was create a table in the db called version, and stored a version number in there. When the script is ran, it compared the version number in the database with that in the php script. And perform whatever it needs to "upgrade" it to the new version, and then updates the version number in the database.
Of couse, if the version table does not exist, the code will create it and mark it as storing version zero.
只需在函数中放置一个计数器即可。如果计数器大于 0,则不执行任何操作。计数器变量应该是静态的,以便它可以在多次调用中“记住”。
至于确保一个文件只执行一次,只需使用“include_once()”而不是“include()”。
Just put a counter in the function. If the counter is greater that 0, then don't do anything. The counter variable should be static so it "remembered" across multiple calls.
As for making sure a file is only executed once, just use "include_once()" instead of "include()".