Aleix
Aleix

Reputation: 497

Run PHP script only first time even if 100.000 users access it at the same time

The title is pretty clear:

I have a PHP file and I want it to be executed only the first time even if 100.000 users try to access it at the same time.

Upvotes: 1

Views: 440

Answers (4)

David Müller
David Müller

Reputation: 5351

You could do this with a lock file you write to the server, like:

if (!is_file("visited_once.txt"))
{
    //you're the one
    file_put_contents("visited_once.txt", "");
}

But maybe a database-solution would be more sophisticated as I'm not a 100% sure that the file solution works for 100.000 concurrent requests.

create your table

CREATE TABLE visited
(
    visit int NOT NULL,
    UNIQUE (visit)
);

do something like this on request

try
{
    $db->query("INSERT INTO visited VALUES (0)");
    //you're the one
}
catch (Exception $ex)
{
    //nope! Already visited
}

This uses a unique key and relies on the database consistency.

Upvotes: 2

Zak
Zak

Reputation: 7515

Can you write to a txt file or MySQl table? If so set a character in the text file or a field in the MySQL table to 0, and the first time the PHP script runs, set it to 1, and use an if statement:

RETRIEVE YOUR NUMBER VIA TXT OR MYSQL
$myVar = YOUR NUMBER;

if ($myVar > 0){
//don't run
}
else{
//run
}

Upvotes: 0

freejosh
freejosh

Reputation: 11383

I would write something to a file as a flag that the script is being executed, and at the end of the script delete the file. At the start of the script check if the file exists.

e.g.:

$flag_file = 'flag.tmp';
if (file_exists($flag_file)) exit();
file_put_contents($flag_file, 1);

// rest of the script

unlink($flag_file);

Upvotes: 0

PieSub
PieSub

Reputation: 318

<?php
if(file_exists('check.txt')) exit;
file_put_contents('check.txt','1');
...your code...
?>

Upvotes: 0

Related Questions