tags:

views:

494

answers:

3

I always used a normal PHP file and just defined the variables in that file, but is this considered best practice?

Example:

<?php

define('DB_PASS', 'p@ssw0rd');

?>
+1  A: 

It is quite safe and I don't think there is any best practice for constants, but I tend to gather them in a dedicated Constants class for readability:

class Constants {
    const DB_PASS = 'mypass';
}
soulmerge
Hmm I like this approach, just for my understanding const and define() work the same?
Phill Pafford
It is almost the same, the important difference being that the the value of a global constant might be an evaluated value (`define('CONSTNAME', $dynamicValue)`), whereas class constants need to be hard-coded basic types (i.e. `const CONSTVALUE = $global` doesn't work). More information on class constants can be found in the php docs: http://www.php.net/manual/en/language.oop5.constants.php
soulmerge
+1  A: 

unless someone has access to your PHP source code that is secure.

however I would make sure the file is outside of the document root to prevent problems IF for some reason php gets turned off on the website and all of a sudden people can see the source of your files :).

Mike Valstar
This is also good advice and don't currently practice this, I never thought about if PHP wasn't running. Thanks
Phill Pafford
+1  A: 

Naming your PHP file something that begins with .ht (for instance .htconfig.inc.php) also helps, since Apache usually has a rule never to serve any files that are named .ht*. But placing your file outside of the document root is even better.

Wim
Interesting take on use of the .ht attribute Apache uses, thnx
Phill Pafford