Tweet
submit to reddit
<? mildcoder ?>
Home | About Me | Contact Us
Categories
  • Security
  • Research
  • Classes
  • Downloads
  • Tutorials
  • News
Search
Advertisements

Common PHP errors, causes and solutions

Php developers often face a set of common errors in different situations; however, the root cause(s) of these errors are ideally the same. It is quite easy to fix these errors once developers understand the problem and are able to locate the wrong or missing code and make the necessary changes.

Here a few such errors and their generic fixes compiled for quick reference. Simply look up the error message from this reference and apply the general fix to the code. If the problem needs further investigation, you can also browse through the links provided to get additional information on how to fix the error.

A List of Common PHP Errors:

Notices

Parse Errors

Warnings

Fatal Errors

  • Allowed memory size of xxxx bytes exhausted (tried to allocate xxx bytes)
  • Call to a member function … on a non-object
  • Call to Undefined function
  • Cannot redeclare xxx
  • Can’t use function return value in write context
  • Declaration of AAA::BBB() must be compatible with that of CCC::BBB() ‘
  • Using $this when not in object context

MySql Errors

  • You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near … at line …

Nothing is seen. The page is empty and white.

The White Page or better known as the Screen of Death, this is a common problem faced when error reporting is disabled. Fatal errors especially syntax errors result in a blank page as the system does not display the corresponding error message on screen.

If the system has been configured to log errors, the complete error message though not flashed on screen, will be recorded in the error log.

Error reporting is usually disabled in the deployed version so that website users are not exposed to syntax and parsing errors. Error logging should always be enabled to keep track and fix script errors accurately, as logs hold valuable information on the erroneous line of code, and the error message.

The simple solution to this problem is to temporarily enable error reporting so that error messages are visible on the screen. This may however cause all errors messages to be visible to all users of the website.

Add the following code at the top of the PHP code to enable error reporting:

1
ini_set('display_errors', 1); error_reporting(~0);

The ini_set() function will enable the display of errors and set error reporting to the highest level to trap all possible errors in the script. However ini_set() works only at run time and does not display syntax or parsing errors, but they are still written to the error log.

To display such errors in the browser window:

Notice: Undefined variable

This notice occurs when a variable is used without being defined previously.

For Example:

1
2
3
4
foreach ($items as $item) {
    // do something with item
    $counter++;
}

This script will trigger a notice if the variable $counter has not been defined earlier in the script. Strict coding standards require the variable to be defined and set with a default value based on the data type before it is used.

In this case the variable initially gets defined and is set to 0 before being incremented.

1
2
3
4
5
$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Notice: Undefined Index

This notice is displayed when a script tries to access an array using a key value that is not present in the array.

The following code is a classic example for an Undefined Index notice:

1
2
3
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];

Both key values, spinach and 1, used to access the array do not exist in $data, causing an E_NOTICE to be raised.

The best way to address this problem is to first check if the offset, index or key value exists in the array before accessing the array element.

Use array_key_exists or isset to check existence of array index.

1
2
3
4
5
6
7
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in array';
}

Notice: Use of undefined constant xxx – assumed ‘xxx’

This notice is again associated with vague definition of tokens. Tokens are assumed as constants based on their usage, but there are no explicit definitions.

Common causes that trigger this notice include:

  • A string used as an associative array key not enclosed within quotes

    • echo $array[key]; // Wrong
    • echo $array['key']; // Right
  • Variable name without a preceding $ (dollar) sign

    • echo varName; // Wrong
    • echo $varName; // Right

Often the notice is also caused when the script tries to access a constant and the library or PHP extension that contains the constant definition is not available in the specified directory.

Parse error: syntax error, unexpected T_XXX

Happens when you have T_XXX token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string, when the entire complex variable construct is not enclosed in{}.

The error case:

This will result in Unexpected T_ENCAPSED_AND_WHITESPACE:

1
echo "This is a double-quoted string with a quoted array key in $array['key']";

Possible fixes:

In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue anE_NOTICE. So the above could be written as:

1
echo "This is a double-quoted string with an un-quoted array key in $array[key]";

The entire complex array variable and key(s) can be enclosed in {}, in which case they should be quoted to avoid an E_NOTICE. The PHP documentation recommends this syntax for complex variables.

1
echo "This is a double-quoted string with a quoted array key in {$array['key']}";

Or a complex array property of an object:

1
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";

Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolate it:

1
echo "This is a double-quoted string with an array variable " . $array['key'] . " concatenated inside.";

For reference, see the section on Variable Parsing in the PHP Strings manual page.

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

This error is seen when a double dot operator : is used twice :: in the script.

This scope resolution operator derives its name “Paamayim Nekudotayim” from its Hebrew equivalent that means a “double colon”.

Warning: Cannot modify header information – headers already sent

This E_WARNING is raised when a HTTP header is sent to the client after an output has been already been received in response to an earlier command. Simply means HTTP header is being sent multiple times in the body of the script. The warning however will not block the script.

Consider the following code as an example:

1
2
3
4
5
6
7
<html>

    <?php session_start(); ?>

    <head><title>My Page</title>

</html>

When this code is executed, the element first gets written to the output stream. The next function session_start() tries to send HTTP headers and the corresponding session cookie to the client. As headers come first in the web server response, PHP sends the headers to the client when it writes the element to the output stream.

Moving the session_start() function to the first line (above ) will fix the error in this example.

To fix this issue:

  • Find the command that raises the warning.
  • Check if there are any statements before this line of code that may send an output to the user.
  • Move any code that sets HTTP header values to the first line of the script.
  • In case complex conditional statements are used, ensure that header is set at the earliest part of the logic.
  • Watch out for extra white spaces or blank lines outside the scope of php start and end tags that also cause a similar warning. These will result in a blank line or space being printed as an output.
  • Avoid Byte Order Marks in the code that are commonly used to indicate script encoding (Example: UTF-8)

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

This warning occurs when a script tries to work on the result set from a failed mysql_query. While the warning will not stop the script, the program may not work correctly.

It is therefore important to check for the result returned by the mysql_query, and proceed to the next step only if the query is successful. Use the following code to check the result.

1
2
3
4
5
6
7
8
9
$res = mysql_query($sql);

if (!$res) {

   die(mysql_error());

}

// fetch data from the result after checking for error