arrays - Reference - What does this error mean in PHP?

529

What is this?

This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix them. This is also a Community Wiki, so everyone is invited to participate adding to and maintaining this list.

Why is this?

Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on Stack Overflow. The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in their particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.

What should I do here?

If your question has been marked as a duplicate of this one, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.

If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.

The List

Also, see:

822

Answer

Solution:

Warning: Cannot modify header information - headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

This is an and it will not stop the script.

A typical example would be a template file like this:

<html>
    <?php session_start(); ?>
    <head><title>My Page</title>
</html>
...

Thesession_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the<html> element to the output stream. You'd have to move thesession_start() to the top.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

An often overlooked output is new lines after PHP's closing?>. It is considered a standard practice to omit?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening<?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.

If your file has more than one<?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

Related Questions:

187

Answer

Solution:

Fatal error: Call to a member function ... on a non-object

Happens with code similar toxyz->method() wherexyz is not an object and therefore thatmethod can not be called.

This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).

Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.

A typical example would be

// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);

In the example above, the query cannot be prepared andprepare() will assignfalse to$statement. Trying to call theexecute() method will then result in the Fatal Error becausefalse is a "non-object" because the value is a boolean.

Figure out why your function returned a boolean instead of an object. For example, check the$pdo object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.

If even the->prepare is failing then your$pdo database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.

Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example

if ($someCondition) {
    $myObj = new MyObj();
}
// ...
$myObj->someMethod();

By attempting to execute the method outside the conditional block, your object may not be defined.

Related Questions:

578

Answer

Solution:

Nothing is seen. The page is empty and white.

Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.

If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g./var/log/apache2 on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).

Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.

This can be easily done by adding at the top of the script the following PHP code:

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

The code will turn on the display of errors and set reporting to the highest level.

Since the is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the directive totrue. Do this either in thephp.ini or in a.htaccess or by any other method that affects the configuration .

You can use the same methods to set the log_errors and error_log directives to choose your own log file location.

Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.

Related questions:

Related errors:

819

Answer

Solution:

"Notice: {-code-1}", or "Warning: Undefined array key"

Happens when you try to access an array by a key that does not exist in the array.

A typical example of an{-code-1} notice would be (demo)

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

Bothspinach and1 do not exist in the array, causing an to be triggered. In PHP 8.0, this is an E_WARNING instead.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using or :

$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in the array';
}

If you have code like:

<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...

then$_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

Related Questions:

545

Answer

Solution:

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

First and foremost:

. They are no longer maintained and are officially deprecated. See the ? Learn about instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result ofmysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned bymysql_query by

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch

Related Questions:

Related Errors:

Othermysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

218

Answer

Solution:

Fatal error: Call to undefined function XXX

Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.

Example 1 - Conditional Function Declaration

$someCondition = false;
if ($someCondition === true) {
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn() will never be declared because$someCondition is not true.

Example 2 - Function in Function Declaration

function createFn() 
{
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn will only be declared oncecreateFn() gets called. Note that subsequent calls tocreateFn() will trigger an error about Redeclaration of an Existing function.

You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.

In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g.apt in Debian or Ubuntu,yum in Red Hat or CentOS), or a control panel in a shared hosting environment.

If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.

In case of missing includes, make sure to include the file declaring the function before calling the function.

In case of typos, fix the typo.

Related Questions:

37



707

Answer

Solution:

MySQL: 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 ...

This error is often caused because you forgot to properly escape the data passed to a MySQL query.

An example of what not to do (the "Bad Idea"):

$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);

This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)

What will happen if the submitted text contains single quotes?$query will end up with:

$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';

And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.

To avoid such errors, you MUST always escape the data before use in a query.

Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!

Documentation:




764
votes

Answer

Solution:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

In PHP 8.0 and above, the message is instead:

syntax error, unexpected string content "", expecting "-" or identifier or variable or number

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 inUnexpected T_ENCAPSED_AND_WHITESPACE:

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 an{-code-4}. So the above could be written as:

{-code-5}

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

{-code-8}

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

{-code-9}

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

75

Answer

---------^^^^^|||E_NOTICE|||echo "This is a double-quoted string with an un-quoted array key in $array[key]"; //
369

Answer

--^^^^^|||{}|||E_NOTICE|||echo "This is a double-quoted string with a quoted array key in {$array['key']}"; //
785

Answer

--^^^^^^^^^^^^^^^ // Or a complex array property of an object: echo "This is a a double-quoted string with a complex {$object->property->array['key']}";|||echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside."; //
119

Answer

--------^^^^^^^^^^^^^^^^^^^^^
235

Answer

Solution:

Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)

There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in thephp.ini file or by usingini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined inphp.ini). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.

The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.

If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The function is your friend.

Related Questions:




780
votes

Answer

Solution:

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually byinclude,require orfopen and PHP couldn't find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more ...

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like__DIR__ ordirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

Related Errors:

962

Answer

Solution:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים‎. which means "double colon".

This error typically happens if you inadvertently put:: in your code.

Related Questions:

Documentation:

318

Answer

Solution:

Notice: Undefined variable

Happens when you try to use a variable that wasn't previously defined.

A typical example would be

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

If you didn't define$counter before, the code above will trigger the notice.

The correct way is to set the variable before using it

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed usinguse

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because thecounter property hasn't been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

899

Answer

Solution:

Notice: Use of undefined constant XXX - assumed 'XXX'

or, in PHP 7.2 or later:

Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)

or, in PHP 8.0 or later:

Error: Undefined constant XXX

This occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.

One of the most common causes of this notice is a failure to quote a string used as an associative array key.

For example:

// Wrong
echo $array[key];

// Right
echo $array['key'];

Another common cause is a missing$ (dollar) sign in front of a variable name:

// Wrong
echo varName;

// Right
echo $varName;

Or perhaps you have misspelled some other constant or keyword:

// Wrong
$foo = fasle;

// Right
$foo = false;

It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.

Related Questions:

55

Answer

Solution:

Fatal error: Cannot redeclare class [class name]

Fatal error: Cannot redeclare [function name]

This means you're either using the same function/class name twice and need to rename one of them, or it is because you have usedrequire orinclude where you should be usingrequire_once orinclude_once.

When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.

Consider the following code:

class.php

<?php

class MyClass
{
    public function doSomething()
    {
        // do stuff here
    }
}

index.php

<?php

function do_stuff()
{
   require 'class.php';
   $obj = new MyClass;
   $obj->doSomething();
}

do_stuff();
do_stuff();

The second call todo_stuff() will produce the error above. By changingrequire torequire_once, we can be certain that the file that contains the definition ofMyClass will only be loaded once, and the error will be avoided.

99

Answer

Solution:

Parse error: syntax error, unexpected T_VARIABLE

Possible scenario

I can't seem to find where my code has gone wrong. Here is my full error:

Parse error: syntax error, unexpected T_VARIABLE on line x

What I am trying

$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';

Answer

Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the. operator. The interpreter stops running your program when it encounters a parse error.

In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.

What you should do is check carefully at the lines around where the error is for any simple mistakes.

That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something calledT_VARIABLE. ThatT_VARIABLE thing is called atoken. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE token in the interpreter's list.

So make sure you enable at leastE_PARSE in yourphp.ini. Parse errors should not exist in production scripts.

I always recommended to add the following statement, while coding:

error_reporting(E_ALL);

PHP error reporting

Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:

  1. NetBeans (a fine piece of beauty, free software) (the best in my opinion)
  2. PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
  3. Eclipse (beauty and the beast, free software)

Related Questions:

267

Answer

Solution:

Notice: Uninitialized string offset:*

As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.

Consider you, are trying to show every letter from$string

$string = 'ABCD'; 
for ($i=0, $len = strlen($string); $i <= $len; $i++){
    echo "$string[$i] \n"; 
}

The above example will generate (online demo):

{-code-4}

And, as soon as the script finishes echoingD you'll get the error, because inside thefor() loop, you have told PHP to show you the from first to fifth string character from'ABCD' Which, exists, but since the loop starts to count from0 and echoesD by the time it reaches to4, it will throw an offset error.

Similar Errors:

23

Answer

Solution:

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case,$users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returnsNULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing thenodeValue property (field) of the first item while it has not been checked if it exists or not in the$result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

317

Answer

Solution:

Warning: open_basedir restriction in effect

This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.

When it appears, it means that access has been forbidden to some files.

The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.

The fix is normally to change the PHP configuration, the related setting is called .

Sometimes the wrong file or directory names are used, the fix is then to use the right ones.

Related Questions:




454
votes

Answer

Solution:

Parse error: syntax error, unexpected '['

This error comes in two variatians:

Variation 1

$arr = [1, 2, 3];

This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:

$arr = array(1, 2, 3);

See also this example from the manual.

Variation 2

$suffix = explode(',', 'foo,bar')[1];

Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:

$parts = explode(',', 'foo,bar');
$suffix = $parts[1];

See also this example from the manual.

346

Answer

Solution:

Warning: [function] expects parameter 1 to be resource, boolean given

(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)

Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

The cURL extension defines another two resource types:

... a cURL handle and a cURL multi handle.

Whenvar_dumped, the values look like this:

$resource = curl_init();
var_dump($resource);

resource(1) of type (curl)

That's all most resources are, a numeric identifier ((1)) of a certain type ((curl)).

You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.


The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returnedfalse instead. For instance, the has this description:

Return Values

Returns a file pointer resource on success, orFALSE on error.

So in this code,$fp will either be aresource(x) of type (stream) orfalse:

$fp = fopen(...);

If you do not check whether thefopen operation succeed or failed and hence whether$fp is a valid resource orfalse and pass$fp to another function which expects a resource, you may get the above error:

$fp   = fopen(...);
$data = fread($fp, 1024);

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

You always need to error check the return value of functions which are trying to allocate a resource and may fail:

$fp = fopen(...);

if (!$fp) {
    trigger_error('Failed to allocate resource');
    exit;
}

$data = fread($fp, 1024);

Related Errors:

349

Answer

Solution:

Warning: Illegal string offset 'XXX'

This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.

Example:

$var = "test";
echo $var["a_key"];

If you think the variable should be an array, see where it comes from and fix the problem there.

829

Answer

Solution:

Code doesn't run/what looks like parts of my PHP code are output

If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in<?php ?> tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.

To actually run your PHP scripts, you need:

  • a web server which executes your script
  • to set the file extension to .php, otherwise the web server won't interpret it as such*
  • to access your .php file via the web server

* Unless you reconfigure it, everything can be configured.

This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:

file://C:/path/to/my/file.php

This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:

http://localhost/my/file.php

You may also want to check whether you're using short open tags<? instead of<?php and your PHP configuration has turned short open tags off.

Also see PHP code is not being executed, instead code shows on the page

301

Answer

Solution:

Notice: Array to string conversion

This simply happens if you try to treat an array as a string:

$arr = array('foo', 'bar');

echo $arr;  // Notice: Array to string conversion
$str = 'Something, ' . $arr;  // Notice: Array to string conversion

An array cannot simply beecho'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:

echo $arr[0];  // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar

Or loop the array:

foreach($arr as $key => $value) {
    echo "array $key = $value";
    // displays first: array 0 = foo
    // displays next:  array 1 = bar
}

If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.

606

Answer

Solution:

Warning: mysql_connect(): Access denied for user 'name'@'host'

This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials ({-code-20}/{-code-21}). So this is typically not a code problem, but a server configuration issue.

632

Answer

Solution:

Warning: Cannot modify header information - headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

This is an and it will not stop the script.

A typical example would be a template file like this:

<html>
    <?php session_start(); ?>
    <head><title>My Page</title>
</html>
...

Thesession_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the<html> element to the output stream. You'd have to move thesession_start() to the top.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

An often overlooked output is new lines after PHP's closing?>. It is considered a standard practice to omit?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening<?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.

If your file has more than one<?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

Related Questions:

325

Answer

Solution:

Fatal error: Call to a member function ... on a non-object

Happens with code similar toxyz->method() wherexyz is not an object and therefore thatmethod can not be called.

This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).

Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.

A typical example would be

// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);

In the example above, the query cannot be prepared andprepare() will assignfalse to$statement. Trying to call theexecute() method will then result in the Fatal Error becausefalse is a "non-object" because the value is a boolean.

Figure out why your function returned a boolean instead of an object. For example, check the$pdo object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.

If even the->prepare is failing then your$pdo database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.

Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example

if ($someCondition) {
    $myObj = new MyObj();
}
// ...
$myObj->someMethod();

By attempting to execute the method outside the conditional block, your object may not be defined.

Related Questions:

279

Answer

Solution:

Nothing is seen. The page is empty and white.

Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.

If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g./var/log/apache2 on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).

Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.

This can be easily done by adding at the top of the script the following PHP code:

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

The code will turn on the display of errors and set reporting to the highest level.

Since the is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the directive totrue. Do this either in thephp.ini or in a.htaccess or by any other method that affects the configuration .

You can use the same methods to set the log_errors and error_log directives to choose your own log file location.

Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.

Related questions:

Related errors:

896

Answer

Solution:

"Notice: {-code-1}", or "Warning: Undefined array key"

Happens when you try to access an array by a key that does not exist in the array.

A typical example of an{-code-1} notice would be (demo)

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

Bothspinach and1 do not exist in the array, causing an to be triggered. In PHP 8.0, this is an E_WARNING instead.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using or :

$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in the array';
}

If you have code like:

<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...

then$_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

Related Questions:

124

Answer

Solution:

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

First and foremost:

. They are no longer maintained and are officially deprecated. See the ? Learn about instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result ofmysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned bymysql_query by

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch

Related Questions:

Related Errors:

Othermysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

914

Answer

Solution:

Fatal error: Call to undefined function XXX

Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.

Example 1 - Conditional Function Declaration

$someCondition = false;
if ($someCondition === true) {
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn() will never be declared because$someCondition is not true.

Example 2 - Function in Function Declaration

function createFn() 
{
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn will only be declared oncecreateFn() gets called. Note that subsequent calls tocreateFn() will trigger an error about Redeclaration of an Existing function.

You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.

In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g.apt in Debian or Ubuntu,yum in Red Hat or CentOS), or a control panel in a shared hosting environment.

If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.

In case of missing includes, make sure to include the file declaring the function before calling the function.

In case of typos, fix the typo.

Related Questions:

155



124

Answer

Solution:

MySQL: 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 ...

This error is often caused because you forgot to properly escape the data passed to a MySQL query.

An example of what not to do (the "Bad Idea"):

$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);

This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)

What will happen if the submitted text contains single quotes?$query will end up with:

$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';

And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.

To avoid such errors, you MUST always escape the data before use in a query.

Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!

Documentation:




410
votes

Answer

Solution:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

In PHP 8.0 and above, the message is instead:

syntax error, unexpected string content "", expecting "-" or identifier or variable or number

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 inUnexpected T_ENCAPSED_AND_WHITESPACE:

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 an{-code-4}. So the above could be written as:

{-code-5}

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

{-code-8}

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

{-code-9}

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

200

Answer

---------^^^^^|||E_NOTICE|||echo "This is a double-quoted string with an un-quoted array key in $array[key]"; //
746

Answer

--^^^^^|||{}|||E_NOTICE|||echo "This is a double-quoted string with a quoted array key in {$array['key']}"; //
69

Answer

--^^^^^^^^^^^^^^^ // Or a complex array property of an object: echo "This is a a double-quoted string with a complex {$object->property->array['key']}";|||echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside."; //
556

Answer

--------^^^^^^^^^^^^^^^^^^^^^
323

Answer

Solution:

Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)

There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in thephp.ini file or by usingini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined inphp.ini). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.

The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.

If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The function is your friend.

Related Questions:




962
votes

Answer

Solution:

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually byinclude,require orfopen and PHP couldn't find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more ...

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like__DIR__ ordirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

Related Errors:

694

Answer

Solution:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים‎. which means "double colon".

This error typically happens if you inadvertently put:: in your code.

Related Questions:

Documentation:

390

Answer

Solution:

Notice: Undefined variable

Happens when you try to use a variable that wasn't previously defined.

A typical example would be

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

If you didn't define$counter before, the code above will trigger the notice.

The correct way is to set the variable before using it

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed usinguse

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because thecounter property hasn't been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

391

Answer

Solution:

Notice: Use of undefined constant XXX - assumed 'XXX'

or, in PHP 7.2 or later:

Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)

or, in PHP 8.0 or later:

Error: Undefined constant XXX

This occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.

One of the most common causes of this notice is a failure to quote a string used as an associative array key.

For example:

// Wrong
echo $array[key];

// Right
echo $array['key'];

Another common cause is a missing$ (dollar) sign in front of a variable name:

// Wrong
echo varName;

// Right
echo $varName;

Or perhaps you have misspelled some other constant or keyword:

// Wrong
$foo = fasle;

// Right
$foo = false;

It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.

Related Questions:

158

Answer

Solution:

Fatal error: Cannot redeclare class [class name]

Fatal error: Cannot redeclare [function name]

This means you're either using the same function/class name twice and need to rename one of them, or it is because you have usedrequire orinclude where you should be usingrequire_once orinclude_once.

When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.

Consider the following code:

class.php

<?php

class MyClass
{
    public function doSomething()
    {
        // do stuff here
    }
}

index.php

<?php

function do_stuff()
{
   require 'class.php';
   $obj = new MyClass;
   $obj->doSomething();
}

do_stuff();
do_stuff();

The second call todo_stuff() will produce the error above. By changingrequire torequire_once, we can be certain that the file that contains the definition ofMyClass will only be loaded once, and the error will be avoided.

702

Answer

Solution:

Parse error: syntax error, unexpected T_VARIABLE

Possible scenario

I can't seem to find where my code has gone wrong. Here is my full error:

Parse error: syntax error, unexpected T_VARIABLE on line x

What I am trying

$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';

Answer

Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the. operator. The interpreter stops running your program when it encounters a parse error.

In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.

What you should do is check carefully at the lines around where the error is for any simple mistakes.

That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something calledT_VARIABLE. ThatT_VARIABLE thing is called atoken. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE token in the interpreter's list.

So make sure you enable at leastE_PARSE in yourphp.ini. Parse errors should not exist in production scripts.

I always recommended to add the following statement, while coding:

error_reporting(E_ALL);

PHP error reporting

Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:

  1. NetBeans (a fine piece of beauty, free software) (the best in my opinion)
  2. PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
  3. Eclipse (beauty and the beast, free software)

Related Questions:

420

Answer

Solution:

Notice: Uninitialized string offset:*

As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.

Consider you, are trying to show every letter from$string

$string = 'ABCD'; 
for ($i=0, $len = strlen($string); $i <= $len; $i++){
    echo "$string[$i] \n"; 
}

The above example will generate (online demo):

{-code-4}

And, as soon as the script finishes echoingD you'll get the error, because inside thefor() loop, you have told PHP to show you the from first to fifth string character from'ABCD' Which, exists, but since the loop starts to count from0 and echoesD by the time it reaches to4, it will throw an offset error.

Similar Errors:

249

Answer

Solution:

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case,$users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returnsNULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing thenodeValue property (field) of the first item while it has not been checked if it exists or not in the$result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

833

Answer

Solution:

Warning: open_basedir restriction in effect

This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.

When it appears, it means that access has been forbidden to some files.

The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.

The fix is normally to change the PHP configuration, the related setting is called .

Sometimes the wrong file or directory names are used, the fix is then to use the right ones.

Related Questions:




830
votes

Answer

Solution:

Parse error: syntax error, unexpected '['

This error comes in two variatians:

Variation 1

$arr = [1, 2, 3];

This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:

$arr = array(1, 2, 3);

See also this example from the manual.

Variation 2

$suffix = explode(',', 'foo,bar')[1];

Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:

$parts = explode(',', 'foo,bar');
$suffix = $parts[1];

See also this example from the manual.

732

Answer

Solution:

Warning: [function] expects parameter 1 to be resource, boolean given

(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)

Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

The cURL extension defines another two resource types:

... a cURL handle and a cURL multi handle.

Whenvar_dumped, the values look like this:

$resource = curl_init();
var_dump($resource);

resource(1) of type (curl)

That's all most resources are, a numeric identifier ((1)) of a certain type ((curl)).

You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.


The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returnedfalse instead. For instance, the has this description:

Return Values

Returns a file pointer resource on success, orFALSE on error.

So in this code,$fp will either be aresource(x) of type (stream) orfalse:

$fp = fopen(...);

If you do not check whether thefopen operation succeed or failed and hence whether$fp is a valid resource orfalse and pass$fp to another function which expects a resource, you may get the above error:

$fp   = fopen(...);
$data = fread($fp, 1024);

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

You always need to error check the return value of functions which are trying to allocate a resource and may fail:

$fp = fopen(...);

if (!$fp) {
    trigger_error('Failed to allocate resource');
    exit;
}

$data = fread($fp, 1024);

Related Errors:

353

Answer

Solution:

Warning: Illegal string offset 'XXX'

This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.

Example:

$var = "test";
echo $var["a_key"];

If you think the variable should be an array, see where it comes from and fix the problem there.

925

Answer

Solution:

Code doesn't run/what looks like parts of my PHP code are output

If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in<?php ?> tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.

To actually run your PHP scripts, you need:

  • a web server which executes your script
  • to set the file extension to .php, otherwise the web server won't interpret it as such*
  • to access your .php file via the web server

* Unless you reconfigure it, everything can be configured.

This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:

file://C:/path/to/my/file.php

This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:

http://localhost/my/file.php

You may also want to check whether you're using short open tags<? instead of<?php and your PHP configuration has turned short open tags off.

Also see PHP code is not being executed, instead code shows on the page

996

Answer

Solution:

Notice: Array to string conversion

This simply happens if you try to treat an array as a string:

$arr = array('foo', 'bar');

echo $arr;  // Notice: Array to string conversion
$str = 'Something, ' . $arr;  // Notice: Array to string conversion

An array cannot simply beecho'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:

echo $arr[0];  // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar

Or loop the array:

foreach($arr as $key => $value) {
    echo "array $key = $value";
    // displays first: array 0 = foo
    // displays next:  array 1 = bar
}

If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.

309

Answer

Solution:

Warning: mysql_connect(): Access denied for user 'name'@'host'

This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials ({-code-20}/{-code-21}). So this is typically not a code problem, but a server configuration issue.

796

Answer

Solution:

Warning: Cannot modify header information - headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

This is an and it will not stop the script.

A typical example would be a template file like this:

<html>
    <?php session_start(); ?>
    <head><title>My Page</title>
</html>
...

Thesession_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the<html> element to the output stream. You'd have to move thesession_start() to the top.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

An often overlooked output is new lines after PHP's closing?>. It is considered a standard practice to omit?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening<?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.

If your file has more than one<?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

Related Questions:

369

Answer

Solution:

Fatal error: Call to a member function ... on a non-object

Happens with code similar toxyz->method() wherexyz is not an object and therefore thatmethod can not be called.

This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).

Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.

A typical example would be

// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);

In the example above, the query cannot be prepared andprepare() will assignfalse to$statement. Trying to call theexecute() method will then result in the Fatal Error becausefalse is a "non-object" because the value is a boolean.

Figure out why your function returned a boolean instead of an object. For example, check the$pdo object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.

If even the->prepare is failing then your$pdo database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.

Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example

if ($someCondition) {
    $myObj = new MyObj();
}
// ...
$myObj->someMethod();

By attempting to execute the method outside the conditional block, your object may not be defined.

Related Questions:

853

Answer

Solution:

Nothing is seen. The page is empty and white.

Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.

If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g./var/log/apache2 on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).

Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.

This can be easily done by adding at the top of the script the following PHP code:

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

The code will turn on the display of errors and set reporting to the highest level.

Since the is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the directive totrue. Do this either in thephp.ini or in a.htaccess or by any other method that affects the configuration .

You can use the same methods to set the log_errors and error_log directives to choose your own log file location.

Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.

Related questions:

Related errors:

982

Answer

Solution:

"Notice: {-code-1}", or "Warning: Undefined array key"

Happens when you try to access an array by a key that does not exist in the array.

A typical example of an{-code-1} notice would be (demo)

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

Bothspinach and1 do not exist in the array, causing an to be triggered. In PHP 8.0, this is an E_WARNING instead.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using or :

$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in the array';
}

If you have code like:

<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...

then$_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

Related Questions:

421

Answer

Solution:

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

First and foremost:

. They are no longer maintained and are officially deprecated. See the ? Learn about instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result ofmysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned bymysql_query by

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch

Related Questions:

Related Errors:

Othermysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

851

Answer

Solution:

Fatal error: Call to undefined function XXX

Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.

Example 1 - Conditional Function Declaration

$someCondition = false;
if ($someCondition === true) {
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn() will never be declared because$someCondition is not true.

Example 2 - Function in Function Declaration

function createFn() 
{
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn will only be declared oncecreateFn() gets called. Note that subsequent calls tocreateFn() will trigger an error about Redeclaration of an Existing function.

You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.

In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g.apt in Debian or Ubuntu,yum in Red Hat or CentOS), or a control panel in a shared hosting environment.

If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.

In case of missing includes, make sure to include the file declaring the function before calling the function.

In case of typos, fix the typo.

Related Questions:

658



592

Answer

Solution:

MySQL: 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 ...

This error is often caused because you forgot to properly escape the data passed to a MySQL query.

An example of what not to do (the "Bad Idea"):

$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);

This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)

What will happen if the submitted text contains single quotes?$query will end up with:

$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';

And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.

To avoid such errors, you MUST always escape the data before use in a query.

Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!

Documentation:




669
votes

Answer

Solution:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

In PHP 8.0 and above, the message is instead:

syntax error, unexpected string content "", expecting "-" or identifier or variable or number

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 inUnexpected T_ENCAPSED_AND_WHITESPACE:

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 an{-code-4}. So the above could be written as:

{-code-5}

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

{-code-8}

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

{-code-9}

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

120

Answer

---------^^^^^|||E_NOTICE|||echo "This is a double-quoted string with an un-quoted array key in $array[key]"; //
800

Answer

--^^^^^|||{}|||E_NOTICE|||echo "This is a double-quoted string with a quoted array key in {$array['key']}"; //
197

Answer

--^^^^^^^^^^^^^^^ // Or a complex array property of an object: echo "This is a a double-quoted string with a complex {$object->property->array['key']}";|||echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside."; //
683

Answer

--------^^^^^^^^^^^^^^^^^^^^^
56

Answer

Solution:

Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)

There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in thephp.ini file or by usingini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined inphp.ini). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.

The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.

If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The function is your friend.

Related Questions:




65
votes

Answer

Solution:

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually byinclude,require orfopen and PHP couldn't find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more ...

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like__DIR__ ordirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

Related Errors:

975

Answer

Solution:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים‎. which means "double colon".

This error typically happens if you inadvertently put:: in your code.

Related Questions:

Documentation:

424

Answer

Solution:

Notice: Undefined variable

Happens when you try to use a variable that wasn't previously defined.

A typical example would be

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

If you didn't define$counter before, the code above will trigger the notice.

The correct way is to set the variable before using it

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed usinguse

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because thecounter property hasn't been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

454

Answer

Solution:

Notice: Use of undefined constant XXX - assumed 'XXX'

or, in PHP 7.2 or later:

Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)

or, in PHP 8.0 or later:

Error: Undefined constant XXX

This occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.

One of the most common causes of this notice is a failure to quote a string used as an associative array key.

For example:

// Wrong
echo $array[key];

// Right
echo $array['key'];

Another common cause is a missing$ (dollar) sign in front of a variable name:

// Wrong
echo varName;

// Right
echo $varName;

Or perhaps you have misspelled some other constant or keyword:

// Wrong
$foo = fasle;

// Right
$foo = false;

It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.

Related Questions:

450

Answer

Solution:

Fatal error: Cannot redeclare class [class name]

Fatal error: Cannot redeclare [function name]

This means you're either using the same function/class name twice and need to rename one of them, or it is because you have usedrequire orinclude where you should be usingrequire_once orinclude_once.

When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.

Consider the following code:

class.php

<?php

class MyClass
{
    public function doSomething()
    {
        // do stuff here
    }
}

index.php

<?php

function do_stuff()
{
   require 'class.php';
   $obj = new MyClass;
   $obj->doSomething();
}

do_stuff();
do_stuff();

The second call todo_stuff() will produce the error above. By changingrequire torequire_once, we can be certain that the file that contains the definition ofMyClass will only be loaded once, and the error will be avoided.

263

Answer

Solution:

Parse error: syntax error, unexpected T_VARIABLE

Possible scenario

I can't seem to find where my code has gone wrong. Here is my full error:

Parse error: syntax error, unexpected T_VARIABLE on line x

What I am trying

$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';

Answer

Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the. operator. The interpreter stops running your program when it encounters a parse error.

In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.

What you should do is check carefully at the lines around where the error is for any simple mistakes.

That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something calledT_VARIABLE. ThatT_VARIABLE thing is called atoken. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE token in the interpreter's list.

So make sure you enable at leastE_PARSE in yourphp.ini. Parse errors should not exist in production scripts.

I always recommended to add the following statement, while coding:

error_reporting(E_ALL);

PHP error reporting

Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:

  1. NetBeans (a fine piece of beauty, free software) (the best in my opinion)
  2. PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
  3. Eclipse (beauty and the beast, free software)

Related Questions:

746

Answer

Solution:

Notice: Uninitialized string offset:*

As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.

Consider you, are trying to show every letter from$string

$string = 'ABCD'; 
for ($i=0, $len = strlen($string); $i <= $len; $i++){
    echo "$string[$i] \n"; 
}

The above example will generate (online demo):

{-code-4}

And, as soon as the script finishes echoingD you'll get the error, because inside thefor() loop, you have told PHP to show you the from first to fifth string character from'ABCD' Which, exists, but since the loop starts to count from0 and echoesD by the time it reaches to4, it will throw an offset error.

Similar Errors:

254

Answer

Solution:

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case,$users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returnsNULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing thenodeValue property (field) of the first item while it has not been checked if it exists or not in the$result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

842

Answer

Solution:

Warning: open_basedir restriction in effect

This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.

When it appears, it means that access has been forbidden to some files.

The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.

The fix is normally to change the PHP configuration, the related setting is called .

Sometimes the wrong file or directory names are used, the fix is then to use the right ones.

Related Questions:




718
votes

Answer

Solution:

Parse error: syntax error, unexpected '['

This error comes in two variatians:

Variation 1

$arr = [1, 2, 3];

This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:

$arr = array(1, 2, 3);

See also this example from the manual.

Variation 2

$suffix = explode(',', 'foo,bar')[1];

Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:

$parts = explode(',', 'foo,bar');
$suffix = $parts[1];

See also this example from the manual.

204

Answer

Solution:

Warning: [function] expects parameter 1 to be resource, boolean given

(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)

Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

The cURL extension defines another two resource types:

... a cURL handle and a cURL multi handle.

Whenvar_dumped, the values look like this:

$resource = curl_init();
var_dump($resource);

resource(1) of type (curl)

That's all most resources are, a numeric identifier ((1)) of a certain type ((curl)).

You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.


The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returnedfalse instead. For instance, the has this description:

Return Values

Returns a file pointer resource on success, orFALSE on error.

So in this code,$fp will either be aresource(x) of type (stream) orfalse:

$fp = fopen(...);

If you do not check whether thefopen operation succeed or failed and hence whether$fp is a valid resource orfalse and pass$fp to another function which expects a resource, you may get the above error:

$fp   = fopen(...);
$data = fread($fp, 1024);

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

You always need to error check the return value of functions which are trying to allocate a resource and may fail:

$fp = fopen(...);

if (!$fp) {
    trigger_error('Failed to allocate resource');
    exit;
}

$data = fread($fp, 1024);

Related Errors:

891

Answer

Solution:

Warning: Illegal string offset 'XXX'

This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.

Example:

$var = "test";
echo $var["a_key"];

If you think the variable should be an array, see where it comes from and fix the problem there.

159

Answer

Solution:

Code doesn't run/what looks like parts of my PHP code are output

If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in<?php ?> tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.

To actually run your PHP scripts, you need:

  • a web server which executes your script
  • to set the file extension to .php, otherwise the web server won't interpret it as such*
  • to access your .php file via the web server

* Unless you reconfigure it, everything can be configured.

This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:

file://C:/path/to/my/file.php

This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:

http://localhost/my/file.php

You may also want to check whether you're using short open tags<? instead of<?php and your PHP configuration has turned short open tags off.

Also see PHP code is not being executed, instead code shows on the page

856

Answer

Solution:

Notice: Array to string conversion

This simply happens if you try to treat an array as a string:

$arr = array('foo', 'bar');

echo $arr;  // Notice: Array to string conversion
$str = 'Something, ' . $arr;  // Notice: Array to string conversion

An array cannot simply beecho'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:

echo $arr[0];  // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar

Or loop the array:

foreach($arr as $key => $value) {
    echo "array $key = $value";
    // displays first: array 0 = foo
    // displays next:  array 1 = bar
}

If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.

48

Answer

Solution:

Warning: mysql_connect(): Access denied for user 'name'@'host'

This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials ({-code-20}/{-code-21}). So this is typically not a code problem, but a server configuration issue.

322

Answer

Solution:

Warning: Cannot modify header information - headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

This is an and it will not stop the script.

A typical example would be a template file like this:

<html>
    <?php session_start(); ?>
    <head><title>My Page</title>
</html>
...

Thesession_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the<html> element to the output stream. You'd have to move thesession_start() to the top.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

An often overlooked output is new lines after PHP's closing?>. It is considered a standard practice to omit?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening<?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.

If your file has more than one<?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

Related Questions:

879

Answer

Solution:

Fatal error: Call to a member function ... on a non-object

Happens with code similar toxyz->method() wherexyz is not an object and therefore thatmethod can not be called.

This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).

Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.

A typical example would be

// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);

In the example above, the query cannot be prepared andprepare() will assignfalse to$statement. Trying to call theexecute() method will then result in the Fatal Error becausefalse is a "non-object" because the value is a boolean.

Figure out why your function returned a boolean instead of an object. For example, check the$pdo object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.

If even the->prepare is failing then your$pdo database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.

Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example

if ($someCondition) {
    $myObj = new MyObj();
}
// ...
$myObj->someMethod();

By attempting to execute the method outside the conditional block, your object may not be defined.

Related Questions:

97

Answer

Solution:

Nothing is seen. The page is empty and white.

Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.

If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g./var/log/apache2 on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).

Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.

This can be easily done by adding at the top of the script the following PHP code:

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

The code will turn on the display of errors and set reporting to the highest level.

Since the is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the directive totrue. Do this either in thephp.ini or in a.htaccess or by any other method that affects the configuration .

You can use the same methods to set the log_errors and error_log directives to choose your own log file location.

Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.

Related questions:

Related errors:

1

Answer

Solution:

"Notice: {-code-1}", or "Warning: Undefined array key"

Happens when you try to access an array by a key that does not exist in the array.

A typical example of an{-code-1} notice would be (demo)

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

Bothspinach and1 do not exist in the array, causing an to be triggered. In PHP 8.0, this is an E_WARNING instead.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using or :

$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in the array';
}

If you have code like:

<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...

then$_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

Related Questions:

525

Answer

Solution:

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

First and foremost:

. They are no longer maintained and are officially deprecated. See the ? Learn about instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result ofmysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned bymysql_query by

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch

Related Questions:

Related Errors:

Othermysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

124

Answer

Solution:

Fatal error: Call to undefined function XXX

Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.

Example 1 - Conditional Function Declaration

$someCondition = false;
if ($someCondition === true) {
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn() will never be declared because$someCondition is not true.

Example 2 - Function in Function Declaration

function createFn() 
{
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn will only be declared oncecreateFn() gets called. Note that subsequent calls tocreateFn() will trigger an error about Redeclaration of an Existing function.

You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.

In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g.apt in Debian or Ubuntu,yum in Red Hat or CentOS), or a control panel in a shared hosting environment.

If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.

In case of missing includes, make sure to include the file declaring the function before calling the function.

In case of typos, fix the typo.

Related Questions:

407



923

Answer

Solution:

MySQL: 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 ...

This error is often caused because you forgot to properly escape the data passed to a MySQL query.

An example of what not to do (the "Bad Idea"):

$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);

This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)

What will happen if the submitted text contains single quotes?$query will end up with:

$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';

And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.

To avoid such errors, you MUST always escape the data before use in a query.

Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!

Documentation:




943
votes

Answer

Solution:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

In PHP 8.0 and above, the message is instead:

syntax error, unexpected string content "", expecting "-" or identifier or variable or number

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 inUnexpected T_ENCAPSED_AND_WHITESPACE:

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 an{-code-4}. So the above could be written as:

{-code-5}

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

{-code-8}

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

{-code-9}

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

386

Answer

---------^^^^^|||E_NOTICE|||echo "This is a double-quoted string with an un-quoted array key in $array[key]"; //
647

Answer

--^^^^^|||{}|||E_NOTICE|||echo "This is a double-quoted string with a quoted array key in {$array['key']}"; //
23

Answer

--^^^^^^^^^^^^^^^ // Or a complex array property of an object: echo "This is a a double-quoted string with a complex {$object->property->array['key']}";|||echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside."; //
293

Answer

--------^^^^^^^^^^^^^^^^^^^^^
409

Answer

Solution:

Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)

There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in thephp.ini file or by usingini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined inphp.ini). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.

The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.

If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The function is your friend.

Related Questions:




448
votes

Answer

Solution:

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually byinclude,require orfopen and PHP couldn't find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more ...

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like__DIR__ ordirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

Related Errors:

366

Answer

Solution:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים‎. which means "double colon".

This error typically happens if you inadvertently put:: in your code.

Related Questions:

Documentation:

325

Answer

Solution:

Notice: Undefined variable

Happens when you try to use a variable that wasn't previously defined.

A typical example would be

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

If you didn't define$counter before, the code above will trigger the notice.

The correct way is to set the variable before using it

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed usinguse

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because thecounter property hasn't been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

130

Answer

Solution:

Notice: Use of undefined constant XXX - assumed 'XXX'

or, in PHP 7.2 or later:

Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)

or, in PHP 8.0 or later:

Error: Undefined constant XXX

This occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.

One of the most common causes of this notice is a failure to quote a string used as an associative array key.

For example:

// Wrong
echo $array[key];

// Right
echo $array['key'];

Another common cause is a missing$ (dollar) sign in front of a variable name:

// Wrong
echo varName;

// Right
echo $varName;

Or perhaps you have misspelled some other constant or keyword:

// Wrong
$foo = fasle;

// Right
$foo = false;

It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.

Related Questions:

635

Answer

Solution:

Fatal error: Cannot redeclare class [class name]

Fatal error: Cannot redeclare [function name]

This means you're either using the same function/class name twice and need to rename one of them, or it is because you have usedrequire orinclude where you should be usingrequire_once orinclude_once.

When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.

Consider the following code:

class.php

<?php

class MyClass
{
    public function doSomething()
    {
        // do stuff here
    }
}

index.php

<?php

function do_stuff()
{
   require 'class.php';
   $obj = new MyClass;
   $obj->doSomething();
}

do_stuff();
do_stuff();

The second call todo_stuff() will produce the error above. By changingrequire torequire_once, we can be certain that the file that contains the definition ofMyClass will only be loaded once, and the error will be avoided.

138

Answer

Solution:

Parse error: syntax error, unexpected T_VARIABLE

Possible scenario

I can't seem to find where my code has gone wrong. Here is my full error:

Parse error: syntax error, unexpected T_VARIABLE on line x

What I am trying

$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';

Answer

Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the. operator. The interpreter stops running your program when it encounters a parse error.

In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.

What you should do is check carefully at the lines around where the error is for any simple mistakes.

That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something calledT_VARIABLE. ThatT_VARIABLE thing is called atoken. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE token in the interpreter's list.

So make sure you enable at leastE_PARSE in yourphp.ini. Parse errors should not exist in production scripts.

I always recommended to add the following statement, while coding:

error_reporting(E_ALL);

PHP error reporting

Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:

  1. NetBeans (a fine piece of beauty, free software) (the best in my opinion)
  2. PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
  3. Eclipse (beauty and the beast, free software)

Related Questions:

701

Answer

Solution:

Notice: Uninitialized string offset:*

As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.

Consider you, are trying to show every letter from$string

$string = 'ABCD'; 
for ($i=0, $len = strlen($string); $i <= $len; $i++){
    echo "$string[$i] \n"; 
}

The above example will generate (online demo):

{-code-4}

And, as soon as the script finishes echoingD you'll get the error, because inside thefor() loop, you have told PHP to show you the from first to fifth string character from'ABCD' Which, exists, but since the loop starts to count from0 and echoesD by the time it reaches to4, it will throw an offset error.

Similar Errors:

966

Answer

Solution:

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case,$users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returnsNULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing thenodeValue property (field) of the first item while it has not been checked if it exists or not in the$result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

216

Answer

Solution:

Warning: open_basedir restriction in effect

This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.

When it appears, it means that access has been forbidden to some files.

The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.

The fix is normally to change the PHP configuration, the related setting is called .

Sometimes the wrong file or directory names are used, the fix is then to use the right ones.

Related Questions:




953
votes

Answer

Solution:

Parse error: syntax error, unexpected '['

This error comes in two variatians:

Variation 1

$arr = [1, 2, 3];

This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:

$arr = array(1, 2, 3);

See also this example from the manual.

Variation 2

$suffix = explode(',', 'foo,bar')[1];

Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:

$parts = explode(',', 'foo,bar');
$suffix = $parts[1];

See also this example from the manual.

461

Answer

Solution:

Warning: [function] expects parameter 1 to be resource, boolean given

(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)

Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

The cURL extension defines another two resource types:

... a cURL handle and a cURL multi handle.

Whenvar_dumped, the values look like this:

$resource = curl_init();
var_dump($resource);

resource(1) of type (curl)

That's all most resources are, a numeric identifier ((1)) of a certain type ((curl)).

You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.


The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returnedfalse instead. For instance, the has this description:

Return Values

Returns a file pointer resource on success, orFALSE on error.

So in this code,$fp will either be aresource(x) of type (stream) orfalse:

$fp = fopen(...);

If you do not check whether thefopen operation succeed or failed and hence whether$fp is a valid resource orfalse and pass$fp to another function which expects a resource, you may get the above error:

$fp   = fopen(...);
$data = fread($fp, 1024);

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

You always need to error check the return value of functions which are trying to allocate a resource and may fail:

$fp = fopen(...);

if (!$fp) {
    trigger_error('Failed to allocate resource');
    exit;
}

$data = fread($fp, 1024);

Related Errors:

321

Answer

Solution:

Warning: Illegal string offset 'XXX'

This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.

Example:

$var = "test";
echo $var["a_key"];

If you think the variable should be an array, see where it comes from and fix the problem there.

538

Answer

Solution:

Code doesn't run/what looks like parts of my PHP code are output

If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in<?php ?> tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.

To actually run your PHP scripts, you need:

  • a web server which executes your script
  • to set the file extension to .php, otherwise the web server won't interpret it as such*
  • to access your .php file via the web server

* Unless you reconfigure it, everything can be configured.

This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:

file://C:/path/to/my/file.php

This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:

http://localhost/my/file.php

You may also want to check whether you're using short open tags<? instead of<?php and your PHP configuration has turned short open tags off.

Also see PHP code is not being executed, instead code shows on the page

93

Answer

Solution:

Notice: Array to string conversion

This simply happens if you try to treat an array as a string:

$arr = array('foo', 'bar');

echo $arr;  // Notice: Array to string conversion
$str = 'Something, ' . $arr;  // Notice: Array to string conversion

An array cannot simply beecho'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:

echo $arr[0];  // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar

Or loop the array:

foreach($arr as $key => $value) {
    echo "array $key = $value";
    // displays first: array 0 = foo
    // displays next:  array 1 = bar
}

If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.

598

Answer

Solution:

Warning: mysql_connect(): Access denied for user 'name'@'host'

This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials ({-code-20}/{-code-21}). So this is typically not a code problem, but a server configuration issue.

113

Answer

Solution:

Warning: Cannot modify header information - headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

This is an and it will not stop the script.

A typical example would be a template file like this:

<html>
    <?php session_start(); ?>
    <head><title>My Page</title>
</html>
...

Thesession_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the<html> element to the output stream. You'd have to move thesession_start() to the top.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

An often overlooked output is new lines after PHP's closing?>. It is considered a standard practice to omit?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening<?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.

If your file has more than one<?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

Related Questions:

469

Answer

Solution:

Fatal error: Call to a member function ... on a non-object

Happens with code similar toxyz->method() wherexyz is not an object and therefore thatmethod can not be called.

This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).

Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.

A typical example would be

// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);

In the example above, the query cannot be prepared andprepare() will assignfalse to$statement. Trying to call theexecute() method will then result in the Fatal Error becausefalse is a "non-object" because the value is a boolean.

Figure out why your function returned a boolean instead of an object. For example, check the$pdo object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.

If even the->prepare is failing then your$pdo database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.

Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example

if ($someCondition) {
    $myObj = new MyObj();
}
// ...
$myObj->someMethod();

By attempting to execute the method outside the conditional block, your object may not be defined.

Related Questions:

531

Answer

Solution:

Nothing is seen. The page is empty and white.

Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.

If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g./var/log/apache2 on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).

Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.

This can be easily done by adding at the top of the script the following PHP code:

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

The code will turn on the display of errors and set reporting to the highest level.

Since the is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the directive totrue. Do this either in thephp.ini or in a.htaccess or by any other method that affects the configuration .

You can use the same methods to set the log_errors and error_log directives to choose your own log file location.

Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.

Related questions:

Related errors:

863

Answer

Solution:

"Notice: {-code-1}", or "Warning: Undefined array key"

Happens when you try to access an array by a key that does not exist in the array.

A typical example of an{-code-1} notice would be (demo)

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

Bothspinach and1 do not exist in the array, causing an to be triggered. In PHP 8.0, this is an E_WARNING instead.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using or :

$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in the array';
}

If you have code like:

<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...

then$_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

Related Questions:

245

Answer

Solution:

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

First and foremost:

. They are no longer maintained and are officially deprecated. See the ? Learn about instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result ofmysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned bymysql_query by

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch

Related Questions:

Related Errors:

Othermysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

997

Answer

Solution:

Fatal error: Call to undefined function XXX

Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.

Example 1 - Conditional Function Declaration

$someCondition = false;
if ($someCondition === true) {
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn() will never be declared because$someCondition is not true.

Example 2 - Function in Function Declaration

function createFn() 
{
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case,fn will only be declared oncecreateFn() gets called. Note that subsequent calls tocreateFn() will trigger an error about Redeclaration of an Existing function.

You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.

In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g.apt in Debian or Ubuntu,yum in Red Hat or CentOS), or a control panel in a shared hosting environment.

If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.

In case of missing includes, make sure to include the file declaring the function before calling the function.

In case of typos, fix the typo.

Related Questions:

542
Write your answer




734

Answer

Solution:

MySQL: 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 ...

This error is often caused because you forgot to properly escape the data passed to a MySQL query.

An example of what not to do (the "Bad Idea"):

$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);

This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)

What will happen if the submitted text contains single quotes?$query will end up with:

$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';

And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.

To avoid such errors, you MUST always escape the data before use in a query.

Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!

Documentation:

Write your answer




235
votes

Answer

Solution:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

In PHP 8.0 and above, the message is instead:

syntax error, unexpected string content "", expecting "-" or identifier or variable or number

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 inUnexpected T_ENCAPSED_AND_WHITESPACE:

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 an{-code-4}. So the above could be written as:

{-code-5}

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

{-code-8}

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

{-code-9}

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

900

Answer

---------^^^^^|||E_NOTICE|||echo "This is a double-quoted string with an un-quoted array key in $array[key]"; //
816

Answer

--^^^^^|||{}|||E_NOTICE|||echo "This is a double-quoted string with a quoted array key in {$array['key']}"; //
237

Answer

--^^^^^^^^^^^^^^^ // Or a complex array property of an object: echo "This is a a double-quoted string with a complex {$object->property->array['key']}";|||echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside."; //
568

Answer

--------^^^^^^^^^^^^^^^^^^^^^
188

Answer

Solution:

Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)

There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in thephp.ini file or by usingini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined inphp.ini). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.

The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.

If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The function is your friend.

Related Questions:

Write your answer




175
votes

Answer

Solution:

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually byinclude,require orfopen and PHP couldn't find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more ...

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like__DIR__ ordirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

Related Errors:

470

Answer

Solution:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים‎. which means "double colon".

This error typically happens if you inadvertently put:: in your code.

Related Questions:

Documentation:

883

Answer

Solution:

Notice: Undefined variable

Happens when you try to use a variable that wasn't previously defined.

A typical example would be

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

If you didn't define$counter before, the code above will trigger the notice.

The correct way is to set the variable before using it

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed usinguse

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because thecounter property hasn't been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

181

Answer

Solution:

Notice: Use of undefined constant XXX - assumed 'XXX'

or, in PHP 7.2 or later:

Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)

or, in PHP 8.0 or later:

Error: Undefined constant XXX

This occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.

One of the most common causes of this notice is a failure to quote a string used as an associative array key.

For example:

// Wrong
echo $array[key];

// Right
echo $array['key'];

Another common cause is a missing$ (dollar) sign in front of a variable name:

// Wrong
echo varName;

// Right
echo $varName;

Or perhaps you have misspelled some other constant or keyword:

// Wrong
$foo = fasle;

// Right
$foo = false;

It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.

Related Questions:

421

Answer

Solution:

Fatal error: Cannot redeclare class [class name]

Fatal error: Cannot redeclare [function name]

This means you're either using the same function/class name twice and need to rename one of them, or it is because you have usedrequire orinclude where you should be usingrequire_once orinclude_once.

When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.

Consider the following code:

class.php

<?php

class MyClass
{
    public function doSomething()
    {
        // do stuff here
    }
}

index.php

<?php

function do_stuff()
{
   require 'class.php';
   $obj = new MyClass;
   $obj->doSomething();
}

do_stuff();
do_stuff();

The second call todo_stuff() will produce the error above. By changingrequire torequire_once, we can be certain that the file that contains the definition ofMyClass will only be loaded once, and the error will be avoided.

210

Answer

Solution:

Parse error: syntax error, unexpected T_VARIABLE

Possible scenario

I can't seem to find where my code has gone wrong. Here is my full error:

Parse error: syntax error, unexpected T_VARIABLE on line x

What I am trying

$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';

Answer

Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the. operator. The interpreter stops running your program when it encounters a parse error.

In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.

What you should do is check carefully at the lines around where the error is for any simple mistakes.

That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something calledT_VARIABLE. ThatT_VARIABLE thing is called atoken. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE token in the interpreter's list.

So make sure you enable at leastE_PARSE in yourphp.ini. Parse errors should not exist in production scripts.

I always recommended to add the following statement, while coding:

error_reporting(E_ALL);

PHP error reporting

Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:

  1. NetBeans (a fine piece of beauty, free software) (the best in my opinion)
  2. PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
  3. Eclipse (beauty and the beast, free software)

Related Questions:

108

Answer

Solution:

Notice: Uninitialized string offset:*

As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.

Consider you, are trying to show every letter from$string

$string = 'ABCD'; 
for ($i=0, $len = strlen($string); $i <= $len; $i++){
    echo "$string[$i] \n"; 
}

The above example will generate (online demo):

{-code-4}

And, as soon as the script finishes echoingD you'll get the error, because inside thefor() loop, you have told PHP to show you the from first to fifth string character from'ABCD' Which, exists, but since the loop starts to count from0 and echoesD by the time it reaches to4, it will throw an offset error.

Similar Errors:

245

Answer

Solution:

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case,$users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returnsNULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing thenodeValue property (field) of the first item while it has not been checked if it exists or not in the$result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

733

Answer

Solution:

Warning: open_basedir restriction in effect

This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.

When it appears, it means that access has been forbidden to some files.

The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.

The fix is normally to change the PHP configuration, the related setting is called .

Sometimes the wrong file or directory names are used, the fix is then to use the right ones.

Related Questions:

Write your answer




619
votes

Answer

Solution:

Parse error: syntax error, unexpected '['

This error comes in two variatians:

Variation 1

$arr = [1, 2, 3];

This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:

$arr = array(1, 2, 3);

See also this example from the manual.

Variation 2

$suffix = explode(',', 'foo,bar')[1];

Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:

$parts = explode(',', 'foo,bar');
$suffix = $parts[1];

See also this example from the manual.

457

Answer

Solution:

Warning: [function] expects parameter 1 to be resource, boolean given

(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)

Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

The cURL extension defines another two resource types:

... a cURL handle and a cURL multi handle.

Whenvar_dumped, the values look like this:

$resource = curl_init();
var_dump($resource);

resource(1) of type (curl)

That's all most resources are, a numeric identifier ((1)) of a certain type ((curl)).

You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.


The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returnedfalse instead. For instance, the has this description:

Return Values

Returns a file pointer resource on success, orFALSE on error.

So in this code,$fp will either be aresource(x) of type (stream) orfalse:

$fp = fopen(...);

If you do not check whether thefopen operation succeed or failed and hence whether$fp is a valid resource orfalse and pass$fp to another function which expects a resource, you may get the above error:

$fp   = fopen(...);
$data = fread($fp, 1024);

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

You always need to error check the return value of functions which are trying to allocate a resource and may fail:

$fp = fopen(...);

if (!$fp) {
    trigger_error('Failed to allocate resource');
    exit;
}

$data = fread($fp, 1024);

Related Errors:

754

Answer

Solution:

Warning: Illegal string offset 'XXX'

This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.

Example:

$var = "test";
echo $var["a_key"];

If you think the variable should be an array, see where it comes from and fix the problem there.

530

Answer

Solution:

Code doesn't run/what looks like parts of my PHP code are output

If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in<?php ?> tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.

To actually run your PHP scripts, you need:

  • a web server which executes your script
  • to set the file extension to .php, otherwise the web server won't interpret it as such*
  • to access your .php file via the web server

* Unless you reconfigure it, everything can be configured.

This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:

file://C:/path/to/my/file.php

This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:

http://localhost/my/file.php

You may also want to check whether you're using short open tags<? instead of<?php and your PHP configuration has turned short open tags off.

Also see PHP code is not being executed, instead code shows on the page

648

Answer

Solution:

Notice: Array to string conversion

This simply happens if you try to treat an array as a string:

$arr = array('foo', 'bar');

echo $arr;  // Notice: Array to string conversion
$str = 'Something, ' . $arr;  // Notice: Array to string conversion

An array cannot simply beecho'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:

echo $arr[0];  // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar

Or loop the array:

foreach($arr as $key => $value) {
    echo "array $key = $value";
    // displays first: array 0 = foo
    // displays next:  array 1 = bar
}

If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.

367

Answer

Solution:

Warning: mysql_connect(): Access denied for user 'name'@'host'

This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials ({-code-20}/{-code-21}). So this is typically not a code problem, but a server configuration issue.

People are also looking for solutions to the problem: PHP Session not working on some(times) mobile users?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.