Storing Simple Values and Parameters – define() PHP constants

Last Updated on: February 11, 2023

In most applications, there is a need for set values that do not change during the execution of a script. Examples of these values are:

  • Database Settings (username, password etc.)
  • Database Table Names
  • Directory Paths
  • Website URLs

A bad way to handle these values is to “hard code” them. This is the process of inserting the values in your code as and when you need them. This will make the values hard to change as the same value will be repeated throughout your application.

A good way to handle these values is to set them as constants and store them in a separate file (or files) and include them in your main scripts. That way a change to these values is easy and you are separating your configuration values from your logic.

A constant is defined as a simple value that cannot change during execution and is a common feature of most programming languages.

When using constants avoid setting them as normal variables as this means it is possible to change or overwrite them. Instead use the PHP function define() to properly set your constants, as follows:

define('MYSQL_DB_NAME', 'cheeseypoofs');

This sets the value ‘localhost’ to the constant MYSQL_DB_NAME. It can be used anywhere like a normal variable, but with global scope:

echo MYSQL_DB_NAME;

mysql_select_db(MYSQL_DB_NAME, $db);

Using constants will help you to keep your application DRY and prevent mismanagement of sensitive credentials.

Be aware that these credentials are available throughout your application, and any file containing sensitive information (e.g. passwords, API keys) should not be committed to a code repository (e.g. git).

In this case, you should look into ENV variables to keep the sensitive data separate from your stored code.


Get notified of new posts:


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *