phpconstantsundefined

What does the PHP error message "Use of undefined constant" mean?


PHP is writing this error in the logs: "Notice: Use of undefined constant".

Error in logs:

PHP Notice:  Use of undefined constant department - assumed 'department' (line 5)
PHP Notice:  Use of undefined constant name - assumed 'name' (line 6)
PHP Notice:  Use of undefined constant email - assumed 'email' (line 7)
PHP Notice:  Use of undefined constant message - assumed 'message' (line 8)

Relevant lines of code:

$department = mysql_real_escape_string($_POST[department]);
$name = mysql_real_escape_string($_POST[name]);
$email = mysql_real_escape_string($_POST[email]);
$message = mysql_real_escape_string($_POST[message]);

What does it mean and why am I seeing it?


Solution

  • Your array keys are strings. String literals must be quoted in PHP:

    $department = mysql_real_escape_string($_POST['department']);
    $name = mysql_real_escape_string($_POST['name']);
    $email = mysql_real_escape_string($_POST['email']);
    $message = mysql_real_escape_string($_POST['message']);
    

    As is, it was looking for constants called department, name, email, message, etc. When it doesn't find such a constant, PHP (bizarrely) interprets it as a string ('department', etc), but warns you about that. Obviously, this can easily break if you do define such a constant later (though it's bad style to have lower-case constants).

    Update: This behavior was later fixed in PHP 8: "If an undefined constant is used an Error is thrown." (PHP: Syntax - Manual)