简体   繁体   中英

Run the code only once in php

I need to run the program only once; afterwards it will run another program. How is it possible?

if()
{
include 'first.php';
}
else
{
include 'second.php';
}

I don't want to put conditions in the if condition.

Please can anyone help?

Store in $_SESSION a flag that marks your first.php has ran once, like this:

if(!isset($_SESSION['first_run'])){
    $_SESSION['first_run'] = 1;
    include 'first.php';
}

include 'second.php';

Use lock files.

$lockfile = '/some/writable/path/executed.lock';
if (file_exists($lockfile)) {
    include('second.php');
} else {
    file_put_contents($lockfile, '');
    include('first.php');
}

just sign with session

if(isset($_SESSION['done'])){    
    $_SESSION['done'] = 'done';    
    include('first.php'); 
}else{    
    include('second.php'); 
}

Let PHP handle that for you with require_once and/or include_once

Inside first.php :

your 
.
.
.
code 
.
.
.
here

define('FIRST_RUN', false);

In your script:

define('FIRST_RUN', true);
include_once 'first.php';

if( !FIRST_RUN )
    include 'second.php'

What did you try???

if(!file_exists('/tmp/foo')) { 
    touch('/tmp/foo');
    include 'first.php'; 
} else { 
    include 'second.php'; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM