1

I have a PHP Code that does some tasks. Lets say someone executes the code by doing so https://localhost/code.php.

I have an employee that executes the script over curl from a separate server, what is the best way to prevent him from launching the script twice, before the (already running) script is actually completed/finished goes to the end.

TLDR: I would need a function, to wait until the task/code (that's running now) completes and the secondary task that is trying to be launched has given (sleep for few seconds or until the first tasks completes).

TLDR2: Looking for function [The title says it]

Any ideas? thanks.

NoCap1
  • 13
  • 2

2 Answers2

0

If you know that there is only one user who will hit your server you can simply use session data.

<?php
session_start();
if (true === $_SESSION["NOT_FINISHED"] ?? false) {
  die("Previous job is not finished yet!");
} else {
  $_SESSION["NOT_FINISHED"] = true;
  // start whatever job need to be done here
  ...
  // when job is done and finished lets release out busy flag
  unset( $_SESSION["NOT_FINISHED"]); 
}
Alex
  • 16,739
  • 1
  • 28
  • 51
  • Hello, thank you unfortunately this doesn't seems to work with **curl** but only when it's executed by a browser. – NoCap1 Nov 25 '19 at 22:27
  • @NoCap1 You just need to keep cookie and send it with curl: https://stackoverflow.com/questions/13020404/keeping-session-alive-with-curl-and-php – Alex Nov 26 '19 at 02:25
  • https://stackoverflow.com/questions/15995919/how-to-use-curl-to-send-cookies – Alex Nov 26 '19 at 02:42
  • I prefer to have no cookies, it'll make things "harder" in some way for some of my customers. – NoCap1 Nov 26 '19 at 10:28
0

While a session won't work with cURL, the idea is valid -- you need to set something persistent outside of your script. So, how about writing to a local file, or writing to a database?

if ( file_exists('lock.txt') ) die;
file_put_contents ('lock.txt', 'This file prevents script execution', LOCK_EX);

(... your script code here...)

unlink ('lock.txt');
FoulFoot
  • 655
  • 5
  • 9