Declaring constants in PHP

Discussion in 'PHP' started by fatabbot, Oct 4, 2006.

  1. #1
    Hello,


    I want to declare several constants that should be accessible in all pages of a website.

    define (STATUS_INACTIVE, 1)
    define (STATUS_ACTIVE, 2)
    ...

    What is the best place to put these defines ?
    If i declare them in xxx.php, can i access the variables only in this specific file ? If not, how and where are constants declared best ?

    Regards,

    Fat Abbot
     
    fatabbot, Oct 4, 2006 IP
  2. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Simply put your contants in a file which is included in all files. Make sure the file cannot be accessed from the internet.

    I would use the format:

    define ('STATUS_INACTIVE', 1);
    define ('STATUS_ACTIVE', 2);
    . . . .

    In one application I have then in an init.php file, which also contains the calls to all the other files which are included in the application.
     
    clancey, Oct 4, 2006 IP
    fatabbot likes this.
  3. penagate

    penagate Guest

    Messages:
    277
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can access them from any files included AFTER the one containing the define statements.

    Use the quote marks around the constant names as demonstrated otherwise it you will get a notice on PHP 5.

    Also you can use something like this:
    if (!defined('IN_APP'))
      die('Remote access prohibited.');
    
    PHP:
    Define IN_APP in your main PHP file and that will prevent direct access to the include files.

    Alternatively you could name them .inc and use a permissions rule in a .htaccess file to throw a 403 on all .inc files.
     
    penagate, Oct 4, 2006 IP
    fatabbot likes this.