在php中只运行一次代码


Run the code only once in php

我只需要运行一次程序;之后它将运行另一个程序。这怎么可能?

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

我不想把条件放在if条件中。

有人能帮忙吗?

在$_SESSION中存储一个标记您的第一个php运行过一次的标志,如下所示:

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

使用锁定文件。

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

只需使用会话进行签名

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

让PHP为您处理require_once和/或include_once

内部first.php:

your 
.
.
.
code 
.
.
.
here
define('FIRST_RUN', false);

在您的脚本中:

define('FIRST_RUN', true);
include_once 'first.php';
if( !FIRST_RUN )
    include 'second.php'

你尝试了什么???

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