The most common PHP Error Messages

(Originally posted on my Portuguese blog at rberaldo.com.br)

Programming languages generate error and warning messages that always indicate issues within the source code. Correctly interpreting these messages often leads to the proper way to fix the problem. However, many beginner programmers don’t analyze these messages due to a lack of knowledge, laziness, or even fear.

I’ll show you here the most common error messages in PHP, along with their main causes and solutions.

Initial Guidelines

Common Error Messages

Enabling All Error Messages

First of all, it’s essential to know that PHP is highly customizable – which can sometimes be a problem. You can disable all error messages or limit them to specific error levels. I won’t explain PHP’s error levels here, but you can learn more about them in this post.

To enable all PHP error messages, simply add the following code at the beginning of your script:

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);

// application code here

For more details, check out this post.

Removing the Error Control Operator

Another thing to note is that you can suppress errors in PHP using the Error Control Operator, the famous “@” symbol. This operator exists to be used, but use it with caution, only when necessary.

Parse Error

Parse errors occur when your code has formatting errors, such as missing or excessive characters. For example:

<?php
phpinfo); ?>

This will return the error:

Parse error: syntax error, unexpected ')' in test.php on line 2

The correction is usually straightforward: analyze the line where the error occurs and look for the character indicated by the error. There may be something missing or extra. Note that the error may not be on the line indicated by the error message; it could be in the previous line. For example:

<?php
echo 'hello' echo 'hello again';
?>

Error message:

Parse error: syntax error, unexpected T_ECHO, expecting ',' or ';' in test.php on line 3

The message says there’s an error on line 3, but it’s actually line 2 causing the problem due to the missing semicolon at the end of the echo.

Unexpected End

“Unexpected end” means the end of the file was encountered earlier than expected. This means that some paired character (such as quotes, brackets, braces, or parentheses) wasn’t closed.

Here’s an example:

$x = 1;
if ($x == 1) {
    echo "x is one";

Notice that we didn’t close the braces for the if block. When you run the above script, it will generate this error:

Parse error: syntax error, unexpected end of file in test.php on line 7

The solution is simple: look for a paired character that was opened but not closed. Proper indentation helps in these cases.

Undefined Index

This error occurs when trying to access a non-existent index of an array. It’s very common with beginners using query strings. The classic example:

<?php
$page = $_GET['p'];
?>

If the “p” variable is not in the URL, it will cause this error:

PHP Notice: Undefined index: pag in test.php on line 2

To avoid this error, always check if the index exists. The isset function can easily solve this problem:

if (isset($_GET['p'])) {
    $p = $_GET['p'];
} else {
    $p = 'default value';
}

The code can also be written using the Ternary Conditional Operator:

$p = isset($_GET['p']) ? $_GET['p'] : 'default_value';

Learn more about the Ternary Operator here.

Undefined Variable

As the error message clearly indicates, this occurs when trying to use an undeclared (or undefined in the case of PHP) variable.

<?php
echo $var;
?>

Error:

PHP Notice: Undefined variable: var in test.php on line 2

The solution is straightforward: create the variable before using it. Of course, the error could have been caused by a typo in the variable name.

Use of Undefined Constant

This error occurs when using a constant before it’s defined. For example:

<?php 

echo ANYTHING;

Running this script will generate the following error:

PHP Notice: Use of undefined constant ANYTHING - assumed 'ANYTHING' in test.php on line 3

In fact, it’s not an error but a notice. In other words, execution continues. PHP assumes that since the constant ANYTHING does not exist, it should display the string “ANYTHING.” This is why even though there is an error, the string “ANYTHING” is displayed on the screen.

It’s very common for beginner programmers who do not use quotes for strings. For example:

$arr = array(
    'key_1' => 'value 1',
    'key_2' => 'value 2',
);

echo $arr[key_1];

Running the code above will generate a NOTICE saying that the constant key_1 does not exist and has been treated as a string. Consequently, the string “value 1” is displayed.

The solution is simple: use quotes for all strings. Otherwise, PHP will attempt to find constants with these names.

Cannot Modify Header Information

This error message is very common for beginners, but the solution is quite simple.

It is related to sending HTTP headers, which involves sessions, cookies, and PHP’s header, session_start, and setcookie functions.

Sending HTTP headers must always occur before any output to the browser, meaning before any HTML code and functions that display data, such as echo, print, print_r, etc. Also, there should be no whitespace in the code before the <?php opening tag.

In short, before functions like session_start, setcookie, and header, there should be NO output to the browser. This includes any HTML code, echo, print, or even a single white space before the PHP opening tag (<?php). If the script generating the error includes or requires another script, make sure to check the other script as well.

Another detail is the Byte Order Mark (BOM). The Byte Order Mark is a character sequence inserted at the beginning of a file to define the byte order. This is another reason for this problem.

So, always use UTF-8 without a BOM, and you won’t have problems.

It is possible to use Output Control Functions, like ob_start and ob_end_clean, to control the output buffer and mitigate the issue of calling functions that send headers after output to the browser.

Call to Undefined Function

Once again, the error is clear: a call to an undefined function has been made.

beraldo();

Error:

Fatal error: Call to undefined function beraldo() in test.php on line 2

To correct this, define the function. There may have been a typo in the function name or a missing inclusion of the defining file.

Class Not Found

This occurs when PHP cannot find the class you want to instantiate.

$b = new Beraldo();

Error:

Fatal error: Class 'beraldo' not found in test.php on line 2

As in the previous error, the solution is to declare the class, check for typos, or ensure the inclusion of the file.

Call to Undefined Method

This occurs when an undefined method of a class is called.

<?php
class Beraldo
{
    public function sayHello()
    {
         echo "hello";
    } 
}

$beraldo = new Beraldo();
$beraldo->sayBye();

Error:

Fatal error: Call to undefined method Beraldo::sayBye() in test.php on line 12

To fix this error, create the method or check for typographical errors in the method name.

Call to a Member Function on a Non-Object

This happens when a method is called on a variable that is not an object instance.

$var = 'hi, I'm a string';
$var->method();

Error:

Fatal error: Call to a member function method() on a non-object in test.php on line 3

To resolve the error, check if you are using the wrong variable or if the original variable’s value has been modified, causing it to lose its object instance.

Supplied Argument Is Not a Valid MySQL Result Resource

This error occurs when a function expects a resource as a parameter, returned by another MySQL function. Most commonly, this error occurs in lines where functions like mysql_fetch_assoc(), mysql_fetch_array(), and similar functions are used. This means that the parameter passed is not a resource returned by mysql_query(), indicating that the query failed, and mysql_query() returned FALSE.

Error message:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in...

The solution is to correct the executed query. Often the error is simple, such as table or field names being incorrect or syntax errors. To view the error returned by MySQL, you can use the mysql_error() function. Therefore, you should execute the query like this:

$exec = mysql_query($your_query_here) or exit(mysql_error());

If the query fails, meaning mysql_query returns FALSE, the exit() function will terminate the script’s execution and display the MySQL error thanks to the mysql_error() function. Reading the error message helps identify the issue in the SQL query.

IMPORTANT: mysql_* functions (such as mysql_connect, mysql_query, etc.) have been deprecated since PHP 5.5 and will be removed from PHP shortly. It is recommended to use MySQLi or PDO. See more at this link.

The MySQL extension is deprecated and will be removed in the future; use MySQLi or PDO instead

The MySQL extension has been considered obsolete since PHP 5.5. It was removed in PHP 7.

The recommendation is to use the MySQLi extension or the PDO class.

For more details, see this article.

Invalid Argument Supplied for foreach()

This error occurs when the argument passed to the foreach loop is not an array.

$var = '';
foreach ($var as $k) {
    echo $k;
}

Error:

Warning: Invalid argument supplied for foreach() in test.php on line 3

As $var is a string, the error occurred. To fix it, you need to check if the parameter is correct and if it hasn’t been modified during script execution, changing it from an array to something else.

Parse Error: Syntax Error, Unexpected ‘[‘

This error often occurs when trying to use the new array definition syntax, which is only available from PHP 5.4 onwards.

Before PHP 5.4, the only accepted syntax for creating arrays was as follows, using the array function:

$arr = array(
    'uno',
    'due',
    'tre'
);

From PHP 5.4 onwards, you can use square brackets, like this:

$arr = ['one', 'two', 'three'];

For more details on array syntax, refer to the PHP Manual.

Conclusion

Error messages are generally very clear. Therefore, read them carefully before asking someone or creating a forum post about them. Many errors can be easily fixed by paying close attention to error messages.

Related posts

14 Thoughts to “The most common PHP Error Messages”

  1. Sempre via usar o @ como um pogzinho
    mas acho que dependendo do caso é uma solução bem viavel 😛

  2. Josué Moura

    Nossa valeu muitíssimo mesmo pelas dicas, poderia me confirmar se a colocar @ na maioria das linhas que me apresentou erro estou fazendo errado….Grato

    1. Usar o operador @ não é muito aconselhável. Depende da situação.

      Leia esta seção do post e os links de referência para entender melhor: http://www.rberaldo.com.br/blog/as-mensagens-de-erros-mais-comuns-do-php/#err_op

  3. Anderson

    Amigo vou te dizer uma coisa Sou tec. de Enfermagem em São Paulo tenho, 30 anos e 10 nessa humilhante profissão, estudo em casa para me motivar algo novo em minha vida o PHP, MySQL, é muito difícil. Seu tutorial o Undefined Index me ajudou, estou 2 dias tentando descobrir como e consegui graças ao eu site, Muito obrigado!

    1. Olá, Anderson.

      Obrigado! É sempre bom saber que um dos meus posts foi útil pra alguém. 🙂

      Abraço

  4. Dyeison

    Muito bom. Estava tendo problemas com o Undefined Index, mas seu artigo me ajudou.
    abraco

  5. Olá Beraldo, gostaria de um help seu, no meu caso o erro é “Call to undefined function”, mas a particularidade é a seguinte:

    No arquivo aonde quero salvar a função a coloquei dentro de uma classe, ai dá o erro, se ficar de fora não dá

    Procurei o arquivo que tem o code para inicializar as classes ( __autoload) e fiz um include do mesmo no arquivo que chama a função, mas o erro persiste.

    Pode me ajudar?

    Att,
    Erick

    1. Olá, Erick

      Se a função está em uma classe, você deve instanciar a classe primeiro. Mesmo usando autoload, deve chamar a referência para a classe.

      Outra alternativa é tornar o método estático (static). Aí basta chamar NomeDaClasse::NomeDoMétodo()

      Abraço

  6. Wíverson Gomes

    Olá bom dia! Belo post. Mas eu gostaria de saber no erro sobre undefined index no php.
    Onde tem o trecho do código
    if ( isset( $_GET[‘pag’] ) )
    {
    $pag = $_GET[‘pag’];
    }
    else
    {
    $pag = ‘valor padrão’;
    }

    o que seria esse ‘valor padrão’.
    Você poderia exemplificar para mim?
    Obrigado.

  7. como resolver esses erro no phpnueke 8.3.2 Warning: ob_start(): second array member is not a valid method in C:wampwwwhtmlmainfile.php on line 86

    Call Stack

    # Time Memory Function Location

    1 0.0570 152904 {main}( ) ..index.php:0

    2 0.0680 523840 require_once( ‘C:wampwwwhtmlmainfile.php’ ) ..index.php:14

    3 0.0680 524816 ob_start ( ) ..mainfile.php:86

    1. Olá. Nunca tinha visto esse erro. Pesquisando no Google, achei pessoas com o mesmo problema, rodando versões bem antigas do PHP. Qual é a versão do PHP que você está usando?

      1. Ops desculpe a demora a versão do php é a 5.6.12 server local apache 2.4.9 mysql 5.6.17 obrigado por sua atenção!

  8. Davi

    eu tenho esse problema pode me ajudar ?
    e esse o erro que estou resebendo : Notice: Undefined variable: erro in /storage/ssd2/825/3063825/public_html/zyro/7.php on line 83

    1. Olá
      Falo sobre esse erro na seção Undefined Variable deste post. Leia novamente, que explico tudo lá

Leave a Comment