Search code examples
phpsessionissetrequire-once

create variable only once in php


I have been looking for a way to run one piece of code only once in php. I want to create and set a variable at the beginning of the webpage and whenever I call that file, the code will ignore that line.

I found this in which there are basically two suggestions: setting a session variable and creating a lock file which I don't want to since there might be many users at the same time and I need to have a lock file for each one of them.

I tried the first option but it doesn't work.

Here are my two files:

config.php

<?php 
     if (at the beginning){
         $variable = something
         echo 'hello';
     }
     else
          do something
?>

second.php

<?php
     require_once 'config.php'    
     //do some other stuff
?>

Whenever second.php is called, it prints 'hello' in the webpage, so if (at the beginning) returns true even though it is not at the beginning. Note that, I check whether at the beginning by if(!isset($_SESSION['done'])){ $_SESSION['done'] = 'done'; }

I wonder what is my mistake and how can I solve the problem. Any help is appreciated.


Solution

  • The program flow for config.php should be:

    <?php 
         session_start();
    
         if (!isset($_SESSION['done'])) {
             $_SESSION['done'] = 1;
             echo 'hello';
         }
         else {
             // do something
         }
    ?>