PHP – Lesson 06: Constants

What Are Constants?

The Unchanging “Variable”

While a “constant” is not a specific data type, it is a type of variable. Specifically, it is a variable that is not changeable. Here are some hard and fast rules about constants:

  • Constants are always in UPPER_CASE
  • Constants are defined by the programmer
  • Constants cannot change within the life of the current script

Some reasons you might want to use constants (but not limited to):

  • for unchanging database connections
  • for file upload parameters
  • for directory pathways
  • in general, to assign an unchanging value to a variable to help avoid security holes


Defining a constant

The way we define a constant is with the define() function, and it takes this basic syntax:

define("CONSTANT_NAME", value);

Here’s an example where we define a numeric value to create a maximum upload size for a form:

define("MAX_WIDTH", 1024);

To see it in a browser, you would simply type:


And it would output to the browser: 1024

Notice how the constant does not have quotes around it in the echo command! If you put quotes around it, it will be read as a string and output: MAX_WIDTH

If we wanted to increase the increment of that constant, we could not do so. If, for instance, you were to type echo MAX_WIDTH++; it would throw an error to the screen because the constant cannot be changed.