AJAX Call - recieve a Notice: Undefined index [duplicate] - javascript

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
Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)
Code doesn't run/what looks like parts of my PHP code are output
Warning: Cannot modify header information - headers already sent
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
Warning: [function] expects parameter 1 to be resource, boolean given
Warning: [function]: failed to open stream: [reason]
Warning: open_basedir restriction in effect
Warning: Division by zero
Warning: Illegal string offset 'XXX'
Warning: count(): Parameter must be an array or an object that implements Countable
Parse error: syntax error, unexpected '['
Parse error: syntax error, unexpected T_XXX
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
Parse error: syntax error, unexpected T_VARIABLE
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
Fatal error: Maximum execution time of XX seconds exceeded
Fatal error: Call to a member function ... on a non-object or null
Fatal Error: Call to Undefined function XXX
Fatal Error: Cannot redeclare XXX
Fatal error: Can't use function return value in write context
Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB()'
Return type of AAA::BBB() should either be compatible with CCC::BBB(), or the #[\ReturnTypeWillChange] attribute should be used
Fatal error: Using $this when not in object context
Fatal error: Object of class Closure could not be converted to string
Fatal error: Undefined class constant
Fatal error: Uncaught TypeError: Argument #n must be of type x, y given
Notice: Array to string conversion (< PHP 8.0) or Warning: Array to string conversion (>= PHP 8.0)
Notice: Trying to get property of non-object error
Notice: Undefined variable or property
"Notice: Undefined Index", or "Warning: Undefined array key"
Notice: Undefined offset XXX [Reference]
Notice: Uninitialized string offset: XXX
Notice: Use of undefined constant XXX - assumed 'XXX' / Error: Undefined constant XXX
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 ...
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Warning: function expects parameter X to be boolean/string/integer
HTTP Error 500 - Internal server error
Deprecated: Arrays and strings offset access syntax with curly braces is deprecated
Also, see:
Reference - What does this symbol mean in PHP?

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 E_WARNING 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>
...
The session_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 the session_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:
Headers already sent by PHP
All PHP "Headers already sent" Questions on Stackoverflow
Byte Order Mark
What PHP Functions Create Output?

Fatal error: Call to a member function ... on a non-object
Happens with code similar to xyz->method() where xyz is not an object and therefore that method 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 and prepare() will assign false to $statement. Trying to call the execute() method will then result in the Fatal Error because false 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:
Call to a member function on a non-object
List all PHP "Fatal error: Call to a member function ... on a non-object" Questions on Stackoverflow

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 ini_set() 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 display_startup_errors directive to true. Do this either in the php.ini or in a .htaccess or by any other method that affects the configuration before runtime.
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:
PHP's white screen of death
White screen of death!
PHP Does Not Display Error Messages
PHP emitting 500 on errors - where is this documented?
How to get useful error messages in PHP?
All PHP "White Page of Death" Questions on Stackoverflow
Related errors:
Parse error: syntax error, unexpected T_XXX
Fatal error: Call to a member function ... on a non-object
Code doesn't run/what looks like parts of my PHP code are output

"Notice: Undefined Index", 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 Undefined Index notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach and 1 do not exist in the array, causing an E_NOTICE 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 array_key_exists or isset:
$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:
Reference: “Notice: Undefined variable” and “Notice: Undefined index”
All PHP "Notice: Undefined Index" Questions on Stackoverflow
http://php.net/arrays

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements 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 of mysql_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 by mysql_query by
$res = mysql_query($sql);
if (!$res) {
trigger_error(mysql_error(),E_USER_ERROR);
}
// after checking, do the fetch
Related Questions:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
All "mysql_fetch_array() expects parameter 1 to be resource, boolean given" Questions on Stackoverflow
Related Errors:
Warning: [function] expects parameter 1 to be resource, boolean given
Other mysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

Fatal error: Using $this when not in object context
$this is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
If a non-static method is called statically. Example:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
How to fix: review your code again, $this can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Use self::$static_property to access the static property.
If code from a class method has been copied over into a normal function or just the global scope and keeping the $this special variable.
How to fix: Review the code and replace $this with a different substitution variable.
Related Questions:
Call non-static method as static: PHP Fatal error: Using $this when not in object context
Copy over code: Fatal error: Using $this when not in object context
All "Using $this when not in object context" Questions on Stackoverflow

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 once createFn() gets called. Note that subsequent calls to createFn() 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:
https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function

Parse error: syntax error, unexpected T_XXX
Happens when you have T_XXX token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
Reference: PHP Parse/Syntax Errors; and How to solve them?
Parse Error: syntax error: unexpected '{'
Parse error: Syntax error, unexpected end of file in my PHP code
Parse error: syntax error, unexpected '<' in - Fix?
Parse error: syntax error, unexpected '?'
For further help see:
http://phpcodechecker.com/ - Which does provide some more helpful explanations on your syntax woes.

Fatal error: Can't use function return value in write context
This usually happens when using a function directly with empty.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty() must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false. Expressions (like is_null(null) in the example) will always be deemed to exist, so here empty is only checking if it is equal to false. You could replace empty() here with !, e.g. if (!is_null(null)), or explicitly compare to false, e.g. if (is_null(null) == false).
Related Questions:
Fatal error: Can't use function the return value

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:
How can I prevent SQL injection in PHP?
mysql_real_escape_string()
mysqli_real_escape_string()
How does the SQL injection from the "Bobby Tables" XKCD comic work?
SQL injection that gets around mysql_real_escape_string()

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 in Unexpected 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 E_NOTICE. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}, in which case they should be quoted to avoid an E_NOTICE. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page

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 the php.ini file or by using ini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined in php.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 memory_get_usage function is your friend.
Related Questions:
All "Fatal error: Allowed memory size of XXX bytes exhausted" Questions on Stackoverflow

Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by include, require or fopen 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__ or dirname(__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:
Troubleshooting checklist: Failed to open stream
Related Errors:
Warning: open_basedir restriction in effect

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:
Reference: PHP Parse/Syntax Errors; and How to solve them?
What do two colons mean in PHP?
What's the difference between :: (double colon) and -> (arrow) in PHP?
Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
Documentation:
Scope Resolution Operator (::)

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 using use
$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 the counter property hasn't been set.
$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
// do something with item
$obj->counter++;
}
Related Questions:
All PHP "Notice: Undefined Variable" Questions on Stackoverflow
"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

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:
What does the PHP error message “Notice: Use of undefined constant” mean?

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 used require or include where you should be using require_once or include_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 to do_stuff() will produce the error above. By changing require to require_once, we can be certain that the file that contains the definition of MyClass will only be loaded once, and the error will be avoided.

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 called T_VARIABLE. That T_VARIABLE thing is called a token. 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.
Good read: List of Parser Tokens
So make sure you enable at least E_PARSE in your php.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:
NetBeans (a fine piece of beauty, free software) (the best in my opinion)
PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
Eclipse (beauty and the beast, free software)
Related Questions:
Reference: PHP Parse/Syntax Errors; and How to solve them?

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):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D you'll get the error, because inside the for() 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 from 0 and echoes D by the time it reaches to 4, it will throw an offset error.
Similar Errors:
Illegal string offset 'option 1'

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 returns NULL 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 the nodeValue 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:
Notice: Undefined Index
Fatal error: Call to a member function ... on a non-object

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 open_basedir.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
open_basedir restriction in effect. File(/) is not within the allowed path(s):
All PHP "Warning: open_basedir restriction in effect" Querstions on Stackoverflow

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.

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.
When var_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 returned false instead. For instance, the fopen function has this description:
Return Values
Returns a file pointer resource on success, or FALSE on error.
So in this code, $fp will either be a resource(x) of type (stream) or false:
$fp = fopen(...);
If you do not check whether the fopen operation succeed or failed and hence whether $fp is a valid resource or false 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:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

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.

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

Warning: Array to string conversion
Notice: Array to string conversion
(A notice until PHP 7.4, since PHP 8.0 a warning)
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 be echo'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.

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 (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on mysql_connect("localhost", "user", "pw") for examples.
Check that you actually used a $username and $password.
It's uncommon that you gain access using no password - which is what happened when the Warning: said (using password: NO).
Only the local test server usually allows to connect with username root, no password, and the test database name.
You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like $, escape them, or put the password in single quotes.
Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'#'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be "localhost", which normally utilizes a local named socket when available. Othertimes you can try "127.0.0.1" as fallback.
Should your MySQL/MariaDB server listen on a different port, then use "servername:3306".
If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g. DB_USER or DB_PASSWORD, check that they're actually defined.
If you get a "Warning: Access defined for 'DB_USER'#'host'" and a "Notice: use of undefined constant 'DB_PASS'", then that's your problem.
Verify that your e.g. xy/db-config.php was actually included and whatelse.
Check for correctly set GRANT permissions.
It's not sufficient to have a username+password pair.
Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for mysql_query calls, if you don't have permissions to SELECT from a specific table, or INSERT/UPDATE, and more commonly DELETE anything.
You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'#'localhost';
If the warning shows up first with Warning: mysql_query(): Access denied for user ''#'localhost' then you may have a php.ini-preconfigured account/password pair.
Check that mysql.default_user= and mysql.default_password= have meaningful values.
Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
Serverfault: mysql access denied for 'root'#'name of the computer'
Warning: mysql_connect(): Access denied
Warning: mysql_select_db() Access denied for user ''#'localhost' (using password: NO)
Access denied for user 'root'#'localhost' with PHPMyAdmin
Btw, you probably don't want to use mysql_* functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.
$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");

Deprecated: Array and string offset access syntax with curly braces is deprecated
String offsets and array elements could be accessed by curly braces {} prior to PHP 7.4.0:
$string = 'abc';
echo $string{0}; // a
$array = [1, 2, 3];
echo $array{0}; // 1
This has been deprecated since PHP 7.4.0 and generates a warning:
Deprecated: Array and string offset access syntax with curly braces is deprecated
You must use square brackets [] to access string offsets and array elements:
$string = 'abc';
echo $string[0]; // a
$array = [1, 2, 3];
echo $array[0]; // 1
The RFC for this change links to a PHP script which attempts to fix this mechanically.

Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator # before the expression. For example:
$value = #(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you either should not divide, or you should change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
warning: division by zero
Warning: Division By Zero Working on PHP and MySQL
Division by zero error in WordPress Theme
How to suppress the “Division by zero” error
How to catch a division by zero?

Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT flag in your error_reporting() settings.
Example :
class HTML {
public function br() {
echo '<br>';
}
}
HTML::br() or $html::br()
You can actually avoid this error by not adding E_STRICT to error_reporting(), eg
error_reporting(E_ALL & ~E_STRICT);
since as for PHP 5.4.0 and above, E_STRICT is included in E_ALL [ref]. But that is not adviceable. The solution is to define your intended static function as actual static :
public static function br() {
echo '<br>';
}
or call the function conventionally :
$html = new HTML();
$html->br();
Related questions :
How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

Related

Undefined array key "class" (View: /var/www/html/evitals/resources/views/caregiver/dashboard/recentUploads.blade.php) [duplicate]

I'm running a PHP script and continue to receive errors like:
Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10
Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11
Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11
Line 10 and 11 looks like this:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
What is the meaning of these error messages?
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
How do I fix them?
This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.
Related Meta discussion:
What can be done about repetitive questions?
Do “reference questions” make sense?
Notice / Warning: Undefined variable
Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue an error of E_WARNING level.
This warning helps a programmer to spot a misspelled variable name. Besides, there are other possible issues with uninitialized variables. As it's stated in the PHP manual,
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.
Means being uninitialized in the main file, this variable may be rewritten by a variable from the included file, that may lead to unpredictable results. To avoid that, all variables in a php file are best to be initialized
Ways to deal with the issue:
Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() to check if they are declared before referencing them, as in:
//Initializing a variable
$value = ""; //Initialization value; 0 for int, [] for array, etc.
echo $value; // no error
Suppress the error with null coalescing operator.
// Null coalescing operator
echo $value ?? '';
For the ancient PHP versions (< 7.0) isset() with ternary can be used
echo isset($value) ? $value : '';
Be aware though, that it's still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.
Suppress the error with the # operator. Left here for the historical reasons but seriously, it just shouldn't happen.
Note: It's strongly recommended to implement just point 1.
Notice: Undefined index / Undefined offset / Warning: Undefined array key
This notice/warning appears when you (or PHP) try to access an undefined index of an array.
Ways to deal with the issue are pretty much the same:
Recommended: Declare your array elements:
//Initializing a variable
$array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
echo $array['value']; // no error
Suppress the error with null coalescing operator":
echo $_POST['value'] ?? '';
With arrays this operator is more justified, because it can be used with outside variables you don't have control for. Therefore, consider using it for the outside variables only, such as $_POST / $_GET / $_SESSION or JSON input. While all internal arrays are best to be predefined/initialized first.
Better yet, validate all input, assign it to local variables, and use them all the way in the code. So every variable you're going to access deliberately exists.
Related:
Notice: Undefined variable
Notice: Undefined Index
Try these
Q1: this notice means $varname is not
defined at current scope of the
script.
Q2: Use of isset(), empty() conditions before using any suspicious variable works well.
// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';
// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
$user_name = $_SESSION['user_name'];
}
Or, as a quick and dirty solution:
// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);
Note about sessions:
When using sessions, session_start(); is required to be placed inside all files using sessions.
http://php.net/manual/en/features.sessions.php
Error display # operator
For undesired and redundant notices, one could use the dedicated # operator to »hide« undefined variable/index messages.
$var = #($_GET["optional_param"]);
This is usually discouraged. Newcomers tend to way overuse it.
It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.
There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect #-hidden notices with: set_error_handler("var_dump");
Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.
Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add # or isset only after verifying functionality.
Fix the cause first. Not the notices.
# is mainly acceptable for $_GET/$_POST input parameters, specifically if they're optional.
And since this covers the majority of such questions, let's expand on the most common causes:
$_GET / $_POST / $_REQUEST undefined input
First thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Is this an expected key name and present on each page request?
Variable names and array indicies are case-sensitive in PHP.
Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:
var_dump($_GET);
var_dump($_POST);
//print_r($_REQUEST);
Both will reveal if your script was invoked with the right or any parameters at all.
Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:
POST parameters and GET input will be be shown separately.
For $_GET parameters you can also peek at the QUERY_STRING in
print_r($_SERVER);
PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well.
You can also look at supplied raw $_COOKIES and other HTTP request headers that way.
More obviously look at your browser address bar for GET parameters:
http://example.org/script.php?id=5&sort=desc
The name=value pairs after the ? question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"] and $_GET["sort"].
Finally check your <form> and <input> declarations, if you expect a parameter but receive none.
Ensure each required input has an <input name=FOO>
The id= or title= attribute does not suffice.
A method=POST form ought to populate $_POST.
Whereas a method=GET (or leaving it out) would yield $_GET variables.
It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.
With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_REQUEST['vars'] again, which mashes GET and POST params.
If you are employing mod_rewrite, then you should check both the access.log as well as enable the RewriteLog to figure out absent parameters.
$_FILES
The same sanity checks apply to file uploads and $_FILES["formname"].
Moreover check for enctype=multipart/form-data
As well as method=POST in your <form> declaration.
See also: PHP Undefined index error $_FILES?
$_COOKIE
The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.
Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.
Generally because of "bad programming", and a possibility for mistakes now or later.
If it's a mistake, make a proper assignment to the variable first: $varname=0;
If it really is only defined sometimes, test for it: if (isset($varname)), before using it
If it's because you spelled it wrong, just correct that
Maybe even turn of the warnings in you PHP-settings
It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.
I didn't want to disable notice because it's helpful, but I wanted to avoid too much typing.
My solution was this function:
function ifexists($varname)
{
return(isset($$varname) ? $varname : null);
}
So if I want to reference to $name and echo if exists, I simply write:
<?= ifexists('name') ?>
For array elements:
function ifexistsidx($var,$index)
{
return(isset($var[$index]) ? $var[$index] : null);
}
In a page if I want to refer to $_REQUEST['name']:
<?= ifexistsidx($_REQUEST, 'name') ?>
It’s because the variable '$user_location' is not getting defined. If you are using any if loop inside, which you are declaring the '$user_location' variable, then you must also have an else loop and define the same. For example:
$a = 10;
if($a == 5) {
$user_location = 'Paris';
}
else {
}
echo $user_location;
The above code will create an error as the if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:
$a = 10;
if($a == 5) {
$user_location='Paris';
}
else {
$user_location='SOMETHING OR BLANK';
}
echo $user_location;
The best way for getting the input string is:
$value = filter_input(INPUT_POST, 'value');
This one-liner is almost equivalent to:
if (!isset($_POST['value'])) {
$value = null;
} elseif (is_array($_POST['value'])) {
$value = false;
} else {
$value = $_POST['value'];
}
If you absolutely want a string value, just like:
$value = (string)filter_input(INPUT_POST, 'value');
In reply to ""Why do they appear all of a sudden? I used to use this script for years and I've never had any problem."
It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.
The other critical setting is the errors can be hidden (i.e. display_errors set to "off" or "syslog").
What will have happened in this case is that either the error_reporting was changed to also show notices (as per examples) and/or that the settings were changed to display_errors on screen (as opposed to suppressing them/logging them).
Why have they changed?
The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.
However it is also possible to override these settings in
.htconf (webserver configuration, including vhosts and sub-configurations)*
.htaccess
in php code itself
and any of these could also have been changed.
There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.
(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)
Summary
Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.
Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed
Check error_reporting and display_errors php directives in .htaccess have not changed
If you have directive in .htaccess, check if they are still permitted in the .htconf file
Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.
The quick fix is to assign your variable to null at the top of your code:
$user_location = null;
Why is this happening?
Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is E_STRICT, which became turned on by default as of PHP 5.4.0.
Furthermore, according to PHP documentation, by default, E_NOTICE is disabled in file php.ini. PHP documentation recommends turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.
; Common Values:
; E_ALL (Show all errors, warnings and notices including coding standards.)
; E_ALL & ~E_NOTICE (Show all errors, except for notices)
; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
Notice that error_reporting is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.
To answer your question, however, this error pops up now when it did not pop up before because:
You installed PHP and the new default settings are somewhat poorly documented but do not exclude E_NOTICE.
E_NOTICE warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keeping E_NOTICE enabled forced me to declare my variables. It made it a LOT easier to learn C. In C, not declaring variables is much bigger of a nuisance.
What can I do about it?
Turn off E_NOTICE by copying the "Default value" E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED and replacing it with what is currently uncommented after the equals sign in error_reporting =. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini file. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.
Turn off E_NOTICE on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache 2, Nginx, or whatever your server of choice is. In Apache, you would use php_value inside of <Directory>.
Rewrite your code to be cleaner. If you need to do this while moving to a production environment or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see display_errors and log_errors in php.ini and your server settings).
To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of ~E_STRICT and ~E_DEPRECATED to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.
What do the errors mean?
Undefined variable: my_variable_name - This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future and makes it easier to read/learn the code.
function foo()
{
$my_variable_name = '';
//....
if ($my_variable_name) {
// perform some logic
}
}
Undefined index: my_index - This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.
// verbose way - generally better
if (isset($my_array['my_index'])) {
echo "My index value is: " . $my_array['my_index'];
}
// non-verbose ternary example - I use this sometimes for small rules.
$my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
echo "My index value is: " . $my_index_val;
Another option is to declare an empty array at the top of your function. This is not always possible.
$my_array = array(
'my_index' => ''
);
//...
$my_array['my_index'] = 'new string';
(Additional tip)
When I was encountering these and other issues, I used NetBeanss IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).
I used to curse this error, but it can be helpful to remind you to escape user input.
For instance, if you thought this was clever, shorthand code:
// Echo whatever the hell this is
<?=$_POST['something']?>
...Think again! A better solution is:
// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>
(I use a custom html() function to escape characters, your mileage may vary)
In PHP 7.0 it's now possible to use the null coalescing operator:
echo "My index value is: " . ($my_array["my_index"] ?? '');
Is equals to:
echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');
PHP manual PHP 7.0
I use my own useful function, exst(), all time which automatically declares variables.
Your code will be -
$greeting = "Hello, " . exst($user_name, 'Visitor') . " from " . exst($user_location);
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* #param mixed $var
* #param mixed $default
*
* #return mixed
*/
function exst(& $var, $default = "")
{
$t = "";
if (!isset($var) || !$var) {
if (isset($default) && $default != "")
$t = $default;
}
else {
$t = $var;
}
if (is_string($t))
$t = trim($t);
return $t;
}
In a very simple language:
The mistake is you are using a variable $user_location which is not defined by you earlier, and it doesn't have any value. So I recommend you to please declare this variable before using it. For example: $user_location = '';Or $user_location = 'Los Angles';
This is a very common error you can face. So don't worry; just declare the variable and enjoy coding.
Keep things simple:
<?php
error_reporting(E_ALL); // Making sure all notices are on
function idxVal(&$var, $default = null) {
return empty($var) ? $var = $default : $var;
}
echo idxVal($arr['test']); // Returns null without any notice
echo idxVal($arr['hey ho'], 'yo'); // Returns yo and assigns it to the array index. Nice
?>
An undefined index means in an array you requested for an unavailable array index. For example,
<?php
$newArray[] = {1, 2, 3, 4, 5};
print_r($newArray[5]);
?>
An undefined variable means you have used completely not an existing variable or which is not defined or initialized by that name. For example,
<?php print_r($myvar); ?>
An undefined offset means in an array you have asked for a nonexisting key. And the solution for this is to check before use:
php> echo array_key_exists(1, $myarray);
Regarding this part of the question:
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
No definite answers but here are a some possible explanations of why settings can 'suddenly' change:
You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.
You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)
You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.
Usually notices don't get displayed / reported (see PHP manual)
so it is possible that when setting up the server, the php.ini file could not be loaded for some reason (file permissions??) and you were on the default settings. Later on, the 'bug' has been solved (by accident) and now it CAN load the correct php.ini file with the error_reporting set to show notices.
Using a ternary operator is simple, readable, and clean:
Pre PHP 7
Assign a variable to the value of another variable if it's set, else assign null (or whatever default value you need):
$newVariable = isset($thePotentialData) ? $thePotentialData : null;
PHP 7+
The same except using the null coalescing operator. There's no longer a need to call isset() as this is built in, and no need to provide the variable to return as it's assumed to return the value of the variable being checked:
$newVariable = $thePotentialData ?? null;
Both will stop the Notices from the OP's question, and both are the exact equivalent of:
if (isset($thePotentialData)) {
$newVariable = $thePotentialData;
} else {
$newVariable = null;
}
If you don't require setting a new variable then you can directly use the ternary operator's returned value, such as with echo, function arguments, etc.:
Echo:
echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';
Function:
$foreName = getForeName(isset($userId) ? $userId : null);
function getForeName($userId)
{
if ($userId === null) {
// Etc
}
}
The above will work just the same with arrays, including sessions, etc., replacing the variable being checked with e.g.:
$_SESSION['checkMe']
Or however many levels deep you need, e.g.:
$clients['personal']['address']['postcode']
Suppression:
It is possible to suppress the PHP Notices with # or reduce your error reporting level, but it does not fix the problem. It simply stops it being reported in the error log. This means that your code still tried to use a variable that was not set, which may or may not mean something doesn't work as intended - depending on how crucial the missing value is.
You should really be checking for this issue and handling it appropriately, either serving a different message, or even just returning a null value for everything else to identify the precise state.
If you just care about the Notice not being in the error log, then as an option you could simply ignore the error log.
If working with classes you need to make sure you reference member variables using $this:
class Person
{
protected $firstName;
protected $lastName;
public function setFullName($first, $last)
{
// Correct
$this->firstName = $first;
// Incorrect
$lastName = $last;
// Incorrect
$this->$lastName = $last;
}
}
Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.
I.e.:
$query = "SELECT col1 FROM table WHERE col_x = ?";
Then trying to access more columns/rows inside a loop.
I.e.:
print_r($row['col1']);
print_r($row['col2']); // undefined index thrown
or in a while loop:
while( $row = fetching_function($query) ) {
echo $row['col1'];
echo "<br>";
echo $row['col2']; // undefined index thrown
echo "<br>";
echo $row['col3']; // undefined index thrown
}
Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.
Consult the followning Q&A's on Stack:
Are table names in MySQL case sensitive?
mysql case sensitive table names in queries
MySql - Case Sensitive issue of tables in different server
One common cause of a variable not existing after an HTML form has been submitted is the form element is not contained within a <form> tag:
Example: Element not contained within the <form>
<form action="example.php" method="post">
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
Example: Element now contained within the <form>
<form action="example.php" method="post">
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
These errors occur whenever we are using a variable that is not set.
The best way to deal with these is set error reporting on while development.
To set error reporting on:
ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);
On production servers, error reporting is off, therefore, we do not get these errors.
On the development server, however, we can set error reporting on.
To get rid of this error, we see the following example:
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
We can initialize the variables to NULL before assigning their values or using them.
So, we can modify the code as:
$test = NULL;
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
This will not disturb any program logic and will not produce a Notice even if $test does not have a value.
So, basically, it’s always better to set error reporting ON for development.
And fix all the errors.
And on production, error reporting should be set to off.
I asked a question about this and I was referred to this post with the message:
This question already has an answer here:
“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
Undefined offset” using PHP
I am sharing my question and solution here:
This is the error:
Line 154 is the problem. This is what I have in line 154:
153 foreach($cities as $key => $city){
154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
I think the problem is that I am writing if conditions for the variable $city, which is not the key but the value in $key => $city. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?
UPDATE 1: The problem is that when executing $citiesCounterArray[$key], sometimes the $key corresponds to a key that does not exist in the $citiesCounterArray array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if $key exists in the array, then run the code, otherwise, skip it.
UPDATE 2: This is how I fixed it by using array_key_exists():
foreach($cities as $key => $city){
if(array_key_exists($key, $citiesCounterArray)){
if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
Probably you were using an old PHP version until and now upgraded PHP that’s the reason it was working without any error till now from years.
Until PHP 4 there was no error if you are using variable without defining it but as of PHP 5 onwards it throws errors for codes like mentioned in question.
If you are sending data to an API, simply use isset():
if(isset($_POST['param'])){
$param = $_POST['param'];
} else {
# Do something else
}
If it is an error is because of a session, make sure you have started the session properly.
Those notices are because you don't have the used variable defined and my_index key was not present into $my_array variable.
Those notices were triggered every time, because your code is not correct, but probably you didn't have the reporting of notices on.
Solve the bugs:
$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;
if(isset($my_array["my_index"])){
echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
}
Another way to get this out:
ini_set("error_reporting", false)
When dealing with files, a proper enctype and a POST method are required, which will trigger an undefined index notice if either are not included in the form.
The manual states the following basic syntax:
HTML
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Reference:
POST method uploads
In PHP you need first to define the variable. After that you can use it.
We can check if a variable is defined or not in a very efficient way!
// If you only want to check variable has value and value has true and false value.
// But variable must be defined first.
if($my_variable_name){
}
// If you want to check if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){
}
Simple Explanation
// It will work with: true, false, and NULL
$defineVariable = false;
if($defineVariable){
echo "true";
}else{
echo "false";
}
// It will check if the variable is defined or not and if the variable has a null value.
if(isset($unDefineVariable)){
echo "true";
}else{
echo "false";
}

AJAX JSON parsing from php file error on the hosting [duplicate]

I'm running a PHP script and continue to receive errors like:
Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10
Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11
Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11
Line 10 and 11 looks like this:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
What is the meaning of these error messages?
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
How do I fix them?
This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.
Related Meta discussion:
What can be done about repetitive questions?
Do “reference questions” make sense?
Notice / Warning: Undefined variable
Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue an error of E_WARNING level.
This warning helps a programmer to spot a misspelled variable name. Besides, there are other possible issues with uninitialized variables. As it's stated in the PHP manual,
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.
Means being uninitialized in the main file, this variable may be rewritten by a variable from the included file, that may lead to unpredictable results. To avoid that, all variables in a php file are best to be initialized
Ways to deal with the issue:
Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() to check if they are declared before referencing them, as in:
//Initializing a variable
$value = ""; //Initialization value; 0 for int, [] for array, etc.
echo $value; // no error
Suppress the error with null coalescing operator.
// Null coalescing operator
echo $value ?? '';
For the ancient PHP versions (< 7.0) isset() with ternary can be used
echo isset($value) ? $value : '';
Be aware though, that it's still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.
Suppress the error with the # operator. Left here for the historical reasons but seriously, it just shouldn't happen.
Note: It's strongly recommended to implement just point 1.
Notice: Undefined index / Undefined offset / Warning: Undefined array key
This notice/warning appears when you (or PHP) try to access an undefined index of an array.
Ways to deal with the issue are pretty much the same:
Recommended: Declare your array elements:
//Initializing a variable
$array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
echo $array['value']; // no error
Suppress the error with null coalescing operator":
echo $_POST['value'] ?? '';
With arrays this operator is more justified, because it can be used with outside variables you don't have control for. Therefore, consider using it for the outside variables only, such as $_POST / $_GET / $_SESSION or JSON input. While all internal arrays are best to be predefined/initialized first.
Better yet, validate all input, assign it to local variables, and use them all the way in the code. So every variable you're going to access deliberately exists.
Related:
Notice: Undefined variable
Notice: Undefined Index
Try these
Q1: this notice means $varname is not
defined at current scope of the
script.
Q2: Use of isset(), empty() conditions before using any suspicious variable works well.
// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';
// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
$user_name = $_SESSION['user_name'];
}
Or, as a quick and dirty solution:
// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);
Note about sessions:
When using sessions, session_start(); is required to be placed inside all files using sessions.
http://php.net/manual/en/features.sessions.php
Error display # operator
For undesired and redundant notices, one could use the dedicated # operator to »hide« undefined variable/index messages.
$var = #($_GET["optional_param"]);
This is usually discouraged. Newcomers tend to way overuse it.
It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.
There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect #-hidden notices with: set_error_handler("var_dump");
Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.
Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add # or isset only after verifying functionality.
Fix the cause first. Not the notices.
# is mainly acceptable for $_GET/$_POST input parameters, specifically if they're optional.
And since this covers the majority of such questions, let's expand on the most common causes:
$_GET / $_POST / $_REQUEST undefined input
First thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Is this an expected key name and present on each page request?
Variable names and array indicies are case-sensitive in PHP.
Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:
var_dump($_GET);
var_dump($_POST);
//print_r($_REQUEST);
Both will reveal if your script was invoked with the right or any parameters at all.
Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:
POST parameters and GET input will be be shown separately.
For $_GET parameters you can also peek at the QUERY_STRING in
print_r($_SERVER);
PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well.
You can also look at supplied raw $_COOKIES and other HTTP request headers that way.
More obviously look at your browser address bar for GET parameters:
http://example.org/script.php?id=5&sort=desc
The name=value pairs after the ? question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"] and $_GET["sort"].
Finally check your <form> and <input> declarations, if you expect a parameter but receive none.
Ensure each required input has an <input name=FOO>
The id= or title= attribute does not suffice.
A method=POST form ought to populate $_POST.
Whereas a method=GET (or leaving it out) would yield $_GET variables.
It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.
With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_REQUEST['vars'] again, which mashes GET and POST params.
If you are employing mod_rewrite, then you should check both the access.log as well as enable the RewriteLog to figure out absent parameters.
$_FILES
The same sanity checks apply to file uploads and $_FILES["formname"].
Moreover check for enctype=multipart/form-data
As well as method=POST in your <form> declaration.
See also: PHP Undefined index error $_FILES?
$_COOKIE
The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.
Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.
Generally because of "bad programming", and a possibility for mistakes now or later.
If it's a mistake, make a proper assignment to the variable first: $varname=0;
If it really is only defined sometimes, test for it: if (isset($varname)), before using it
If it's because you spelled it wrong, just correct that
Maybe even turn of the warnings in you PHP-settings
It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.
I didn't want to disable notice because it's helpful, but I wanted to avoid too much typing.
My solution was this function:
function ifexists($varname)
{
return(isset($$varname) ? $varname : null);
}
So if I want to reference to $name and echo if exists, I simply write:
<?= ifexists('name') ?>
For array elements:
function ifexistsidx($var,$index)
{
return(isset($var[$index]) ? $var[$index] : null);
}
In a page if I want to refer to $_REQUEST['name']:
<?= ifexistsidx($_REQUEST, 'name') ?>
It’s because the variable '$user_location' is not getting defined. If you are using any if loop inside, which you are declaring the '$user_location' variable, then you must also have an else loop and define the same. For example:
$a = 10;
if($a == 5) {
$user_location = 'Paris';
}
else {
}
echo $user_location;
The above code will create an error as the if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:
$a = 10;
if($a == 5) {
$user_location='Paris';
}
else {
$user_location='SOMETHING OR BLANK';
}
echo $user_location;
The best way for getting the input string is:
$value = filter_input(INPUT_POST, 'value');
This one-liner is almost equivalent to:
if (!isset($_POST['value'])) {
$value = null;
} elseif (is_array($_POST['value'])) {
$value = false;
} else {
$value = $_POST['value'];
}
If you absolutely want a string value, just like:
$value = (string)filter_input(INPUT_POST, 'value');
In reply to ""Why do they appear all of a sudden? I used to use this script for years and I've never had any problem."
It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.
The other critical setting is the errors can be hidden (i.e. display_errors set to "off" or "syslog").
What will have happened in this case is that either the error_reporting was changed to also show notices (as per examples) and/or that the settings were changed to display_errors on screen (as opposed to suppressing them/logging them).
Why have they changed?
The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.
However it is also possible to override these settings in
.htconf (webserver configuration, including vhosts and sub-configurations)*
.htaccess
in php code itself
and any of these could also have been changed.
There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.
(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)
Summary
Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.
Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed
Check error_reporting and display_errors php directives in .htaccess have not changed
If you have directive in .htaccess, check if they are still permitted in the .htconf file
Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.
The quick fix is to assign your variable to null at the top of your code:
$user_location = null;
Why is this happening?
Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is E_STRICT, which became turned on by default as of PHP 5.4.0.
Furthermore, according to PHP documentation, by default, E_NOTICE is disabled in file php.ini. PHP documentation recommends turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.
; Common Values:
; E_ALL (Show all errors, warnings and notices including coding standards.)
; E_ALL & ~E_NOTICE (Show all errors, except for notices)
; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
Notice that error_reporting is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.
To answer your question, however, this error pops up now when it did not pop up before because:
You installed PHP and the new default settings are somewhat poorly documented but do not exclude E_NOTICE.
E_NOTICE warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keeping E_NOTICE enabled forced me to declare my variables. It made it a LOT easier to learn C. In C, not declaring variables is much bigger of a nuisance.
What can I do about it?
Turn off E_NOTICE by copying the "Default value" E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED and replacing it with what is currently uncommented after the equals sign in error_reporting =. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini file. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.
Turn off E_NOTICE on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache 2, Nginx, or whatever your server of choice is. In Apache, you would use php_value inside of <Directory>.
Rewrite your code to be cleaner. If you need to do this while moving to a production environment or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see display_errors and log_errors in php.ini and your server settings).
To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of ~E_STRICT and ~E_DEPRECATED to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.
What do the errors mean?
Undefined variable: my_variable_name - This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future and makes it easier to read/learn the code.
function foo()
{
$my_variable_name = '';
//....
if ($my_variable_name) {
// perform some logic
}
}
Undefined index: my_index - This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.
// verbose way - generally better
if (isset($my_array['my_index'])) {
echo "My index value is: " . $my_array['my_index'];
}
// non-verbose ternary example - I use this sometimes for small rules.
$my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
echo "My index value is: " . $my_index_val;
Another option is to declare an empty array at the top of your function. This is not always possible.
$my_array = array(
'my_index' => ''
);
//...
$my_array['my_index'] = 'new string';
(Additional tip)
When I was encountering these and other issues, I used NetBeanss IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).
I used to curse this error, but it can be helpful to remind you to escape user input.
For instance, if you thought this was clever, shorthand code:
// Echo whatever the hell this is
<?=$_POST['something']?>
...Think again! A better solution is:
// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>
(I use a custom html() function to escape characters, your mileage may vary)
In PHP 7.0 it's now possible to use the null coalescing operator:
echo "My index value is: " . ($my_array["my_index"] ?? '');
Is equals to:
echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');
PHP manual PHP 7.0
I use my own useful function, exst(), all time which automatically declares variables.
Your code will be -
$greeting = "Hello, " . exst($user_name, 'Visitor') . " from " . exst($user_location);
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* #param mixed $var
* #param mixed $default
*
* #return mixed
*/
function exst(& $var, $default = "")
{
$t = "";
if (!isset($var) || !$var) {
if (isset($default) && $default != "")
$t = $default;
}
else {
$t = $var;
}
if (is_string($t))
$t = trim($t);
return $t;
}
In a very simple language:
The mistake is you are using a variable $user_location which is not defined by you earlier, and it doesn't have any value. So I recommend you to please declare this variable before using it. For example: $user_location = '';Or $user_location = 'Los Angles';
This is a very common error you can face. So don't worry; just declare the variable and enjoy coding.
Keep things simple:
<?php
error_reporting(E_ALL); // Making sure all notices are on
function idxVal(&$var, $default = null) {
return empty($var) ? $var = $default : $var;
}
echo idxVal($arr['test']); // Returns null without any notice
echo idxVal($arr['hey ho'], 'yo'); // Returns yo and assigns it to the array index. Nice
?>
An undefined index means in an array you requested for an unavailable array index. For example,
<?php
$newArray[] = {1, 2, 3, 4, 5};
print_r($newArray[5]);
?>
An undefined variable means you have used completely not an existing variable or which is not defined or initialized by that name. For example,
<?php print_r($myvar); ?>
An undefined offset means in an array you have asked for a nonexisting key. And the solution for this is to check before use:
php> echo array_key_exists(1, $myarray);
Regarding this part of the question:
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
No definite answers but here are a some possible explanations of why settings can 'suddenly' change:
You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.
You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)
You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.
Usually notices don't get displayed / reported (see PHP manual)
so it is possible that when setting up the server, the php.ini file could not be loaded for some reason (file permissions??) and you were on the default settings. Later on, the 'bug' has been solved (by accident) and now it CAN load the correct php.ini file with the error_reporting set to show notices.
Using a ternary operator is simple, readable, and clean:
Pre PHP 7
Assign a variable to the value of another variable if it's set, else assign null (or whatever default value you need):
$newVariable = isset($thePotentialData) ? $thePotentialData : null;
PHP 7+
The same except using the null coalescing operator. There's no longer a need to call isset() as this is built in, and no need to provide the variable to return as it's assumed to return the value of the variable being checked:
$newVariable = $thePotentialData ?? null;
Both will stop the Notices from the OP's question, and both are the exact equivalent of:
if (isset($thePotentialData)) {
$newVariable = $thePotentialData;
} else {
$newVariable = null;
}
If you don't require setting a new variable then you can directly use the ternary operator's returned value, such as with echo, function arguments, etc.:
Echo:
echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';
Function:
$foreName = getForeName(isset($userId) ? $userId : null);
function getForeName($userId)
{
if ($userId === null) {
// Etc
}
}
The above will work just the same with arrays, including sessions, etc., replacing the variable being checked with e.g.:
$_SESSION['checkMe']
Or however many levels deep you need, e.g.:
$clients['personal']['address']['postcode']
Suppression:
It is possible to suppress the PHP Notices with # or reduce your error reporting level, but it does not fix the problem. It simply stops it being reported in the error log. This means that your code still tried to use a variable that was not set, which may or may not mean something doesn't work as intended - depending on how crucial the missing value is.
You should really be checking for this issue and handling it appropriately, either serving a different message, or even just returning a null value for everything else to identify the precise state.
If you just care about the Notice not being in the error log, then as an option you could simply ignore the error log.
If working with classes you need to make sure you reference member variables using $this:
class Person
{
protected $firstName;
protected $lastName;
public function setFullName($first, $last)
{
// Correct
$this->firstName = $first;
// Incorrect
$lastName = $last;
// Incorrect
$this->$lastName = $last;
}
}
Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.
I.e.:
$query = "SELECT col1 FROM table WHERE col_x = ?";
Then trying to access more columns/rows inside a loop.
I.e.:
print_r($row['col1']);
print_r($row['col2']); // undefined index thrown
or in a while loop:
while( $row = fetching_function($query) ) {
echo $row['col1'];
echo "<br>";
echo $row['col2']; // undefined index thrown
echo "<br>";
echo $row['col3']; // undefined index thrown
}
Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.
Consult the followning Q&A's on Stack:
Are table names in MySQL case sensitive?
mysql case sensitive table names in queries
MySql - Case Sensitive issue of tables in different server
One common cause of a variable not existing after an HTML form has been submitted is the form element is not contained within a <form> tag:
Example: Element not contained within the <form>
<form action="example.php" method="post">
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
Example: Element now contained within the <form>
<form action="example.php" method="post">
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
These errors occur whenever we are using a variable that is not set.
The best way to deal with these is set error reporting on while development.
To set error reporting on:
ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);
On production servers, error reporting is off, therefore, we do not get these errors.
On the development server, however, we can set error reporting on.
To get rid of this error, we see the following example:
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
We can initialize the variables to NULL before assigning their values or using them.
So, we can modify the code as:
$test = NULL;
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
This will not disturb any program logic and will not produce a Notice even if $test does not have a value.
So, basically, it’s always better to set error reporting ON for development.
And fix all the errors.
And on production, error reporting should be set to off.
I asked a question about this and I was referred to this post with the message:
This question already has an answer here:
“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
Undefined offset” using PHP
I am sharing my question and solution here:
This is the error:
Line 154 is the problem. This is what I have in line 154:
153 foreach($cities as $key => $city){
154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
I think the problem is that I am writing if conditions for the variable $city, which is not the key but the value in $key => $city. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?
UPDATE 1: The problem is that when executing $citiesCounterArray[$key], sometimes the $key corresponds to a key that does not exist in the $citiesCounterArray array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if $key exists in the array, then run the code, otherwise, skip it.
UPDATE 2: This is how I fixed it by using array_key_exists():
foreach($cities as $key => $city){
if(array_key_exists($key, $citiesCounterArray)){
if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
Probably you were using an old PHP version until and now upgraded PHP that’s the reason it was working without any error till now from years.
Until PHP 4 there was no error if you are using variable without defining it but as of PHP 5 onwards it throws errors for codes like mentioned in question.
If you are sending data to an API, simply use isset():
if(isset($_POST['param'])){
$param = $_POST['param'];
} else {
# Do something else
}
If it is an error is because of a session, make sure you have started the session properly.
Those notices are because you don't have the used variable defined and my_index key was not present into $my_array variable.
Those notices were triggered every time, because your code is not correct, but probably you didn't have the reporting of notices on.
Solve the bugs:
$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;
if(isset($my_array["my_index"])){
echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
}
Another way to get this out:
ini_set("error_reporting", false)
When dealing with files, a proper enctype and a POST method are required, which will trigger an undefined index notice if either are not included in the form.
The manual states the following basic syntax:
HTML
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Reference:
POST method uploads
In PHP you need first to define the variable. After that you can use it.
We can check if a variable is defined or not in a very efficient way!
// If you only want to check variable has value and value has true and false value.
// But variable must be defined first.
if($my_variable_name){
}
// If you want to check if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){
}
Simple Explanation
// It will work with: true, false, and NULL
$defineVariable = false;
if($defineVariable){
echo "true";
}else{
echo "false";
}
// It will check if the variable is defined or not and if the variable has a null value.
if(isset($unDefineVariable)){
echo "true";
}else{
echo "false";
}

Im getting this error Parse error: syntax error, unexpected '$s' (T_VARIABLE) [duplicate]

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
Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)
Code doesn't run/what looks like parts of my PHP code are output
Warning: Cannot modify header information - headers already sent
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
Warning: [function] expects parameter 1 to be resource, boolean given
Warning: [function]: failed to open stream: [reason]
Warning: open_basedir restriction in effect
Warning: Division by zero
Warning: Illegal string offset 'XXX'
Warning: count(): Parameter must be an array or an object that implements Countable
Parse error: syntax error, unexpected '['
Parse error: syntax error, unexpected T_XXX
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
Parse error: syntax error, unexpected T_VARIABLE
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
Fatal error: Maximum execution time of XX seconds exceeded
Fatal error: Call to a member function ... on a non-object or null
Fatal Error: Call to Undefined function XXX
Fatal Error: Cannot redeclare XXX
Fatal error: Can't use function return value in write context
Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB()'
Return type of AAA::BBB() should either be compatible with CCC::BBB(), or the #[\ReturnTypeWillChange] attribute should be used
Fatal error: Using $this when not in object context
Fatal error: Object of class Closure could not be converted to string
Fatal error: Undefined class constant
Fatal error: Uncaught TypeError: Argument #n must be of type x, y given
Notice: Array to string conversion (< PHP 8.0) or Warning: Array to string conversion (>= PHP 8.0)
Notice: Trying to get property of non-object error
Notice: Undefined variable or property
"Notice: Undefined Index", or "Warning: Undefined array key"
Notice: Undefined offset XXX [Reference]
Notice: Uninitialized string offset: XXX
Notice: Use of undefined constant XXX - assumed 'XXX' / Error: Undefined constant XXX
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 ...
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Warning: function expects parameter X to be boolean/string/integer
HTTP Error 500 - Internal server error
Deprecated: Arrays and strings offset access syntax with curly braces is deprecated
Also, see:
Reference - What does this symbol mean in PHP?
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 E_WARNING 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>
...
The session_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 the session_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:
Headers already sent by PHP
All PHP "Headers already sent" Questions on Stackoverflow
Byte Order Mark
What PHP Functions Create Output?
Fatal error: Call to a member function ... on a non-object
Happens with code similar to xyz->method() where xyz is not an object and therefore that method 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 and prepare() will assign false to $statement. Trying to call the execute() method will then result in the Fatal Error because false 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:
Call to a member function on a non-object
List all PHP "Fatal error: Call to a member function ... on a non-object" Questions on Stackoverflow
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 ini_set() 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 display_startup_errors directive to true. Do this either in the php.ini or in a .htaccess or by any other method that affects the configuration before runtime.
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:
PHP's white screen of death
White screen of death!
PHP Does Not Display Error Messages
PHP emitting 500 on errors - where is this documented?
How to get useful error messages in PHP?
All PHP "White Page of Death" Questions on Stackoverflow
Related errors:
Parse error: syntax error, unexpected T_XXX
Fatal error: Call to a member function ... on a non-object
Code doesn't run/what looks like parts of my PHP code are output
"Notice: Undefined Index", 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 Undefined Index notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach and 1 do not exist in the array, causing an E_NOTICE 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 array_key_exists or isset:
$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:
Reference: “Notice: Undefined variable” and “Notice: Undefined index”
All PHP "Notice: Undefined Index" Questions on Stackoverflow
http://php.net/arrays
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements 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 of mysql_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 by mysql_query by
$res = mysql_query($sql);
if (!$res) {
trigger_error(mysql_error(),E_USER_ERROR);
}
// after checking, do the fetch
Related Questions:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
All "mysql_fetch_array() expects parameter 1 to be resource, boolean given" Questions on Stackoverflow
Related Errors:
Warning: [function] expects parameter 1 to be resource, boolean given
Other mysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.
Fatal error: Using $this when not in object context
$this is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
If a non-static method is called statically. Example:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
How to fix: review your code again, $this can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Use self::$static_property to access the static property.
If code from a class method has been copied over into a normal function or just the global scope and keeping the $this special variable.
How to fix: Review the code and replace $this with a different substitution variable.
Related Questions:
Call non-static method as static: PHP Fatal error: Using $this when not in object context
Copy over code: Fatal error: Using $this when not in object context
All "Using $this when not in object context" Questions on Stackoverflow
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 once createFn() gets called. Note that subsequent calls to createFn() 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:
https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function
Parse error: syntax error, unexpected T_XXX
Happens when you have T_XXX token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
Reference: PHP Parse/Syntax Errors; and How to solve them?
Parse Error: syntax error: unexpected '{'
Parse error: Syntax error, unexpected end of file in my PHP code
Parse error: syntax error, unexpected '<' in - Fix?
Parse error: syntax error, unexpected '?'
For further help see:
http://phpcodechecker.com/ - Which does provide some more helpful explanations on your syntax woes.
Fatal error: Can't use function return value in write context
This usually happens when using a function directly with empty.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty() must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false. Expressions (like is_null(null) in the example) will always be deemed to exist, so here empty is only checking if it is equal to false. You could replace empty() here with !, e.g. if (!is_null(null)), or explicitly compare to false, e.g. if (is_null(null) == false).
Related Questions:
Fatal error: Can't use function the return value
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:
How can I prevent SQL injection in PHP?
mysql_real_escape_string()
mysqli_real_escape_string()
How does the SQL injection from the "Bobby Tables" XKCD comic work?
SQL injection that gets around mysql_real_escape_string()
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 in Unexpected 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 E_NOTICE. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}, in which case they should be quoted to avoid an E_NOTICE. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
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 the php.ini file or by using ini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined in php.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 memory_get_usage function is your friend.
Related Questions:
All "Fatal error: Allowed memory size of XXX bytes exhausted" Questions on Stackoverflow
Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by include, require or fopen 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__ or dirname(__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:
Troubleshooting checklist: Failed to open stream
Related Errors:
Warning: open_basedir restriction in effect
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:
Reference: PHP Parse/Syntax Errors; and How to solve them?
What do two colons mean in PHP?
What's the difference between :: (double colon) and -> (arrow) in PHP?
Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
Documentation:
Scope Resolution Operator (::)
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 using use
$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 the counter property hasn't been set.
$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
// do something with item
$obj->counter++;
}
Related Questions:
All PHP "Notice: Undefined Variable" Questions on Stackoverflow
"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
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:
What does the PHP error message “Notice: Use of undefined constant” mean?
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 used require or include where you should be using require_once or include_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 to do_stuff() will produce the error above. By changing require to require_once, we can be certain that the file that contains the definition of MyClass will only be loaded once, and the error will be avoided.
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 called T_VARIABLE. That T_VARIABLE thing is called a token. 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.
Good read: List of Parser Tokens
So make sure you enable at least E_PARSE in your php.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:
NetBeans (a fine piece of beauty, free software) (the best in my opinion)
PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
Eclipse (beauty and the beast, free software)
Related Questions:
Reference: PHP Parse/Syntax Errors; and How to solve them?
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):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D you'll get the error, because inside the for() 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 from 0 and echoes D by the time it reaches to 4, it will throw an offset error.
Similar Errors:
Illegal string offset 'option 1'
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 returns NULL 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 the nodeValue 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:
Notice: Undefined Index
Fatal error: Call to a member function ... on a non-object
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 open_basedir.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
open_basedir restriction in effect. File(/) is not within the allowed path(s):
All PHP "Warning: open_basedir restriction in effect" Querstions on Stackoverflow
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.
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.
When var_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 returned false instead. For instance, the fopen function has this description:
Return Values
Returns a file pointer resource on success, or FALSE on error.
So in this code, $fp will either be a resource(x) of type (stream) or false:
$fp = fopen(...);
If you do not check whether the fopen operation succeed or failed and hence whether $fp is a valid resource or false 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:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
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.
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
Warning: Array to string conversion
Notice: Array to string conversion
(A notice until PHP 7.4, since PHP 8.0 a warning)
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 be echo'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.
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 (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on mysql_connect("localhost", "user", "pw") for examples.
Check that you actually used a $username and $password.
It's uncommon that you gain access using no password - which is what happened when the Warning: said (using password: NO).
Only the local test server usually allows to connect with username root, no password, and the test database name.
You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like $, escape them, or put the password in single quotes.
Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'#'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be "localhost", which normally utilizes a local named socket when available. Othertimes you can try "127.0.0.1" as fallback.
Should your MySQL/MariaDB server listen on a different port, then use "servername:3306".
If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g. DB_USER or DB_PASSWORD, check that they're actually defined.
If you get a "Warning: Access defined for 'DB_USER'#'host'" and a "Notice: use of undefined constant 'DB_PASS'", then that's your problem.
Verify that your e.g. xy/db-config.php was actually included and whatelse.
Check for correctly set GRANT permissions.
It's not sufficient to have a username+password pair.
Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for mysql_query calls, if you don't have permissions to SELECT from a specific table, or INSERT/UPDATE, and more commonly DELETE anything.
You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'#'localhost';
If the warning shows up first with Warning: mysql_query(): Access denied for user ''#'localhost' then you may have a php.ini-preconfigured account/password pair.
Check that mysql.default_user= and mysql.default_password= have meaningful values.
Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
Serverfault: mysql access denied for 'root'#'name of the computer'
Warning: mysql_connect(): Access denied
Warning: mysql_select_db() Access denied for user ''#'localhost' (using password: NO)
Access denied for user 'root'#'localhost' with PHPMyAdmin
Btw, you probably don't want to use mysql_* functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.
$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
Deprecated: Array and string offset access syntax with curly braces is deprecated
String offsets and array elements could be accessed by curly braces {} prior to PHP 7.4.0:
$string = 'abc';
echo $string{0}; // a
$array = [1, 2, 3];
echo $array{0}; // 1
This has been deprecated since PHP 7.4.0 and generates a warning:
Deprecated: Array and string offset access syntax with curly braces is deprecated
You must use square brackets [] to access string offsets and array elements:
$string = 'abc';
echo $string[0]; // a
$array = [1, 2, 3];
echo $array[0]; // 1
The RFC for this change links to a PHP script which attempts to fix this mechanically.
Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator # before the expression. For example:
$value = #(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you either should not divide, or you should change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
warning: division by zero
Warning: Division By Zero Working on PHP and MySQL
Division by zero error in WordPress Theme
How to suppress the “Division by zero” error
How to catch a division by zero?
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT flag in your error_reporting() settings.
Example :
class HTML {
public function br() {
echo '<br>';
}
}
HTML::br() or $html::br()
You can actually avoid this error by not adding E_STRICT to error_reporting(), eg
error_reporting(E_ALL & ~E_STRICT);
since as for PHP 5.4.0 and above, E_STRICT is included in E_ALL [ref]. But that is not adviceable. The solution is to define your intended static function as actual static :
public static function br() {
echo '<br>';
}
or call the function conventionally :
$html = new HTML();
$html->br();
Related questions :
How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

Notice: Undefined index: image - image is not recognized as a defined index [duplicate]

I'm running a PHP script and continue to receive errors like:
Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10
Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11
Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11
Line 10 and 11 looks like this:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
What is the meaning of these error messages?
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
How do I fix them?
This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.
Related Meta discussion:
What can be done about repetitive questions?
Do “reference questions” make sense?
Notice / Warning: Undefined variable
Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue an error of E_WARNING level.
This warning helps a programmer to spot a misspelled variable name. Besides, there are other possible issues with uninitialized variables. As it's stated in the PHP manual,
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.
Means being uninitialized in the main file, this variable may be rewritten by a variable from the included file, that may lead to unpredictable results. To avoid that, all variables in a php file are best to be initialized
Ways to deal with the issue:
Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() to check if they are declared before referencing them, as in:
//Initializing a variable
$value = ""; //Initialization value; 0 for int, [] for array, etc.
echo $value; // no error
Suppress the error with null coalescing operator.
// Null coalescing operator
echo $value ?? '';
For the ancient PHP versions (< 7.0) isset() with ternary can be used
echo isset($value) ? $value : '';
Be aware though, that it's still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.
Suppress the error with the # operator. Left here for the historical reasons but seriously, it just shouldn't happen.
Note: It's strongly recommended to implement just point 1.
Notice: Undefined index / Undefined offset / Warning: Undefined array key
This notice/warning appears when you (or PHP) try to access an undefined index of an array.
Ways to deal with the issue are pretty much the same:
Recommended: Declare your array elements:
//Initializing a variable
$array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
echo $array['value']; // no error
Suppress the error with null coalescing operator":
echo $_POST['value'] ?? '';
With arrays this operator is more justified, because it can be used with outside variables you don't have control for. Therefore, consider using it for the outside variables only, such as $_POST / $_GET / $_SESSION or JSON input. While all internal arrays are best to be predefined/initialized first.
Better yet, validate all input, assign it to local variables, and use them all the way in the code. So every variable you're going to access deliberately exists.
Related:
Notice: Undefined variable
Notice: Undefined Index
Try these
Q1: this notice means $varname is not
defined at current scope of the
script.
Q2: Use of isset(), empty() conditions before using any suspicious variable works well.
// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';
// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
$user_name = $_SESSION['user_name'];
}
Or, as a quick and dirty solution:
// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);
Note about sessions:
When using sessions, session_start(); is required to be placed inside all files using sessions.
http://php.net/manual/en/features.sessions.php
Error display # operator
For undesired and redundant notices, one could use the dedicated # operator to »hide« undefined variable/index messages.
$var = #($_GET["optional_param"]);
This is usually discouraged. Newcomers tend to way overuse it.
It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.
There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect #-hidden notices with: set_error_handler("var_dump");
Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.
Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add # or isset only after verifying functionality.
Fix the cause first. Not the notices.
# is mainly acceptable for $_GET/$_POST input parameters, specifically if they're optional.
And since this covers the majority of such questions, let's expand on the most common causes:
$_GET / $_POST / $_REQUEST undefined input
First thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Is this an expected key name and present on each page request?
Variable names and array indicies are case-sensitive in PHP.
Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:
var_dump($_GET);
var_dump($_POST);
//print_r($_REQUEST);
Both will reveal if your script was invoked with the right or any parameters at all.
Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:
POST parameters and GET input will be be shown separately.
For $_GET parameters you can also peek at the QUERY_STRING in
print_r($_SERVER);
PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well.
You can also look at supplied raw $_COOKIES and other HTTP request headers that way.
More obviously look at your browser address bar for GET parameters:
http://example.org/script.php?id=5&sort=desc
The name=value pairs after the ? question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"] and $_GET["sort"].
Finally check your <form> and <input> declarations, if you expect a parameter but receive none.
Ensure each required input has an <input name=FOO>
The id= or title= attribute does not suffice.
A method=POST form ought to populate $_POST.
Whereas a method=GET (or leaving it out) would yield $_GET variables.
It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.
With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_REQUEST['vars'] again, which mashes GET and POST params.
If you are employing mod_rewrite, then you should check both the access.log as well as enable the RewriteLog to figure out absent parameters.
$_FILES
The same sanity checks apply to file uploads and $_FILES["formname"].
Moreover check for enctype=multipart/form-data
As well as method=POST in your <form> declaration.
See also: PHP Undefined index error $_FILES?
$_COOKIE
The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.
Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.
Generally because of "bad programming", and a possibility for mistakes now or later.
If it's a mistake, make a proper assignment to the variable first: $varname=0;
If it really is only defined sometimes, test for it: if (isset($varname)), before using it
If it's because you spelled it wrong, just correct that
Maybe even turn of the warnings in you PHP-settings
It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.
I didn't want to disable notice because it's helpful, but I wanted to avoid too much typing.
My solution was this function:
function ifexists($varname)
{
return(isset($$varname) ? $varname : null);
}
So if I want to reference to $name and echo if exists, I simply write:
<?= ifexists('name') ?>
For array elements:
function ifexistsidx($var,$index)
{
return(isset($var[$index]) ? $var[$index] : null);
}
In a page if I want to refer to $_REQUEST['name']:
<?= ifexistsidx($_REQUEST, 'name') ?>
It’s because the variable '$user_location' is not getting defined. If you are using any if loop inside, which you are declaring the '$user_location' variable, then you must also have an else loop and define the same. For example:
$a = 10;
if($a == 5) {
$user_location = 'Paris';
}
else {
}
echo $user_location;
The above code will create an error as the if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:
$a = 10;
if($a == 5) {
$user_location='Paris';
}
else {
$user_location='SOMETHING OR BLANK';
}
echo $user_location;
The best way for getting the input string is:
$value = filter_input(INPUT_POST, 'value');
This one-liner is almost equivalent to:
if (!isset($_POST['value'])) {
$value = null;
} elseif (is_array($_POST['value'])) {
$value = false;
} else {
$value = $_POST['value'];
}
If you absolutely want a string value, just like:
$value = (string)filter_input(INPUT_POST, 'value');
In reply to ""Why do they appear all of a sudden? I used to use this script for years and I've never had any problem."
It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.
The other critical setting is the errors can be hidden (i.e. display_errors set to "off" or "syslog").
What will have happened in this case is that either the error_reporting was changed to also show notices (as per examples) and/or that the settings were changed to display_errors on screen (as opposed to suppressing them/logging them).
Why have they changed?
The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.
However it is also possible to override these settings in
.htconf (webserver configuration, including vhosts and sub-configurations)*
.htaccess
in php code itself
and any of these could also have been changed.
There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.
(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)
Summary
Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.
Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed
Check error_reporting and display_errors php directives in .htaccess have not changed
If you have directive in .htaccess, check if they are still permitted in the .htconf file
Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.
The quick fix is to assign your variable to null at the top of your code:
$user_location = null;
Why is this happening?
Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is E_STRICT, which became turned on by default as of PHP 5.4.0.
Furthermore, according to PHP documentation, by default, E_NOTICE is disabled in file php.ini. PHP documentation recommends turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.
; Common Values:
; E_ALL (Show all errors, warnings and notices including coding standards.)
; E_ALL & ~E_NOTICE (Show all errors, except for notices)
; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
Notice that error_reporting is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.
To answer your question, however, this error pops up now when it did not pop up before because:
You installed PHP and the new default settings are somewhat poorly documented but do not exclude E_NOTICE.
E_NOTICE warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keeping E_NOTICE enabled forced me to declare my variables. It made it a LOT easier to learn C. In C, not declaring variables is much bigger of a nuisance.
What can I do about it?
Turn off E_NOTICE by copying the "Default value" E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED and replacing it with what is currently uncommented after the equals sign in error_reporting =. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini file. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.
Turn off E_NOTICE on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache 2, Nginx, or whatever your server of choice is. In Apache, you would use php_value inside of <Directory>.
Rewrite your code to be cleaner. If you need to do this while moving to a production environment or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see display_errors and log_errors in php.ini and your server settings).
To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of ~E_STRICT and ~E_DEPRECATED to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.
What do the errors mean?
Undefined variable: my_variable_name - This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future and makes it easier to read/learn the code.
function foo()
{
$my_variable_name = '';
//....
if ($my_variable_name) {
// perform some logic
}
}
Undefined index: my_index - This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.
// verbose way - generally better
if (isset($my_array['my_index'])) {
echo "My index value is: " . $my_array['my_index'];
}
// non-verbose ternary example - I use this sometimes for small rules.
$my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
echo "My index value is: " . $my_index_val;
Another option is to declare an empty array at the top of your function. This is not always possible.
$my_array = array(
'my_index' => ''
);
//...
$my_array['my_index'] = 'new string';
(Additional tip)
When I was encountering these and other issues, I used NetBeanss IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).
I used to curse this error, but it can be helpful to remind you to escape user input.
For instance, if you thought this was clever, shorthand code:
// Echo whatever the hell this is
<?=$_POST['something']?>
...Think again! A better solution is:
// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>
(I use a custom html() function to escape characters, your mileage may vary)
In PHP 7.0 it's now possible to use the null coalescing operator:
echo "My index value is: " . ($my_array["my_index"] ?? '');
Is equals to:
echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');
PHP manual PHP 7.0
I use my own useful function, exst(), all time which automatically declares variables.
Your code will be -
$greeting = "Hello, " . exst($user_name, 'Visitor') . " from " . exst($user_location);
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* #param mixed $var
* #param mixed $default
*
* #return mixed
*/
function exst(& $var, $default = "")
{
$t = "";
if (!isset($var) || !$var) {
if (isset($default) && $default != "")
$t = $default;
}
else {
$t = $var;
}
if (is_string($t))
$t = trim($t);
return $t;
}
In a very simple language:
The mistake is you are using a variable $user_location which is not defined by you earlier, and it doesn't have any value. So I recommend you to please declare this variable before using it. For example: $user_location = '';Or $user_location = 'Los Angles';
This is a very common error you can face. So don't worry; just declare the variable and enjoy coding.
Keep things simple:
<?php
error_reporting(E_ALL); // Making sure all notices are on
function idxVal(&$var, $default = null) {
return empty($var) ? $var = $default : $var;
}
echo idxVal($arr['test']); // Returns null without any notice
echo idxVal($arr['hey ho'], 'yo'); // Returns yo and assigns it to the array index. Nice
?>
An undefined index means in an array you requested for an unavailable array index. For example,
<?php
$newArray[] = {1, 2, 3, 4, 5};
print_r($newArray[5]);
?>
An undefined variable means you have used completely not an existing variable or which is not defined or initialized by that name. For example,
<?php print_r($myvar); ?>
An undefined offset means in an array you have asked for a nonexisting key. And the solution for this is to check before use:
php> echo array_key_exists(1, $myarray);
Regarding this part of the question:
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
No definite answers but here are a some possible explanations of why settings can 'suddenly' change:
You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.
You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)
You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.
Usually notices don't get displayed / reported (see PHP manual)
so it is possible that when setting up the server, the php.ini file could not be loaded for some reason (file permissions??) and you were on the default settings. Later on, the 'bug' has been solved (by accident) and now it CAN load the correct php.ini file with the error_reporting set to show notices.
Using a ternary operator is simple, readable, and clean:
Pre PHP 7
Assign a variable to the value of another variable if it's set, else assign null (or whatever default value you need):
$newVariable = isset($thePotentialData) ? $thePotentialData : null;
PHP 7+
The same except using the null coalescing operator. There's no longer a need to call isset() as this is built in, and no need to provide the variable to return as it's assumed to return the value of the variable being checked:
$newVariable = $thePotentialData ?? null;
Both will stop the Notices from the OP's question, and both are the exact equivalent of:
if (isset($thePotentialData)) {
$newVariable = $thePotentialData;
} else {
$newVariable = null;
}
If you don't require setting a new variable then you can directly use the ternary operator's returned value, such as with echo, function arguments, etc.:
Echo:
echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';
Function:
$foreName = getForeName(isset($userId) ? $userId : null);
function getForeName($userId)
{
if ($userId === null) {
// Etc
}
}
The above will work just the same with arrays, including sessions, etc., replacing the variable being checked with e.g.:
$_SESSION['checkMe']
Or however many levels deep you need, e.g.:
$clients['personal']['address']['postcode']
Suppression:
It is possible to suppress the PHP Notices with # or reduce your error reporting level, but it does not fix the problem. It simply stops it being reported in the error log. This means that your code still tried to use a variable that was not set, which may or may not mean something doesn't work as intended - depending on how crucial the missing value is.
You should really be checking for this issue and handling it appropriately, either serving a different message, or even just returning a null value for everything else to identify the precise state.
If you just care about the Notice not being in the error log, then as an option you could simply ignore the error log.
If working with classes you need to make sure you reference member variables using $this:
class Person
{
protected $firstName;
protected $lastName;
public function setFullName($first, $last)
{
// Correct
$this->firstName = $first;
// Incorrect
$lastName = $last;
// Incorrect
$this->$lastName = $last;
}
}
Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.
I.e.:
$query = "SELECT col1 FROM table WHERE col_x = ?";
Then trying to access more columns/rows inside a loop.
I.e.:
print_r($row['col1']);
print_r($row['col2']); // undefined index thrown
or in a while loop:
while( $row = fetching_function($query) ) {
echo $row['col1'];
echo "<br>";
echo $row['col2']; // undefined index thrown
echo "<br>";
echo $row['col3']; // undefined index thrown
}
Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.
Consult the followning Q&A's on Stack:
Are table names in MySQL case sensitive?
mysql case sensitive table names in queries
MySql - Case Sensitive issue of tables in different server
One common cause of a variable not existing after an HTML form has been submitted is the form element is not contained within a <form> tag:
Example: Element not contained within the <form>
<form action="example.php" method="post">
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
Example: Element now contained within the <form>
<form action="example.php" method="post">
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
These errors occur whenever we are using a variable that is not set.
The best way to deal with these is set error reporting on while development.
To set error reporting on:
ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);
On production servers, error reporting is off, therefore, we do not get these errors.
On the development server, however, we can set error reporting on.
To get rid of this error, we see the following example:
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
We can initialize the variables to NULL before assigning their values or using them.
So, we can modify the code as:
$test = NULL;
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
This will not disturb any program logic and will not produce a Notice even if $test does not have a value.
So, basically, it’s always better to set error reporting ON for development.
And fix all the errors.
And on production, error reporting should be set to off.
I asked a question about this and I was referred to this post with the message:
This question already has an answer here:
“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
Undefined offset” using PHP
I am sharing my question and solution here:
This is the error:
Line 154 is the problem. This is what I have in line 154:
153 foreach($cities as $key => $city){
154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
I think the problem is that I am writing if conditions for the variable $city, which is not the key but the value in $key => $city. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?
UPDATE 1: The problem is that when executing $citiesCounterArray[$key], sometimes the $key corresponds to a key that does not exist in the $citiesCounterArray array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if $key exists in the array, then run the code, otherwise, skip it.
UPDATE 2: This is how I fixed it by using array_key_exists():
foreach($cities as $key => $city){
if(array_key_exists($key, $citiesCounterArray)){
if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
Probably you were using an old PHP version until and now upgraded PHP that’s the reason it was working without any error till now from years.
Until PHP 4 there was no error if you are using variable without defining it but as of PHP 5 onwards it throws errors for codes like mentioned in question.
If you are sending data to an API, simply use isset():
if(isset($_POST['param'])){
$param = $_POST['param'];
} else {
# Do something else
}
If it is an error is because of a session, make sure you have started the session properly.
Those notices are because you don't have the used variable defined and my_index key was not present into $my_array variable.
Those notices were triggered every time, because your code is not correct, but probably you didn't have the reporting of notices on.
Solve the bugs:
$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;
if(isset($my_array["my_index"])){
echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
}
Another way to get this out:
ini_set("error_reporting", false)
When dealing with files, a proper enctype and a POST method are required, which will trigger an undefined index notice if either are not included in the form.
The manual states the following basic syntax:
HTML
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Reference:
POST method uploads
In PHP you need first to define the variable. After that you can use it.
We can check if a variable is defined or not in a very efficient way!
// If you only want to check variable has value and value has true and false value.
// But variable must be defined first.
if($my_variable_name){
}
// If you want to check if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){
}
Simple Explanation
// It will work with: true, false, and NULL
$defineVariable = false;
if($defineVariable){
echo "true";
}else{
echo "false";
}
// It will check if the variable is defined or not and if the variable has a null value.
if(isset($unDefineVariable)){
echo "true";
}else{
echo "false";
}

INSERT query is not sending through [duplicate]

I'm running a PHP script and continue to receive errors like:
Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10
Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11
Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11
Line 10 and 11 looks like this:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
What is the meaning of these error messages?
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
How do I fix them?
This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.
Related Meta discussion:
What can be done about repetitive questions?
Do “reference questions” make sense?
Notice / Warning: Undefined variable
Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue an error of E_WARNING level.
This warning helps a programmer to spot a misspelled variable name. Besides, there are other possible issues with uninitialized variables. As it's stated in the PHP manual,
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.
Means being uninitialized in the main file, this variable may be rewritten by a variable from the included file, that may lead to unpredictable results. To avoid that, all variables in a php file are best to be initialized
Ways to deal with the issue:
Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() to check if they are declared before referencing them, as in:
//Initializing a variable
$value = ""; //Initialization value; 0 for int, [] for array, etc.
echo $value; // no error
Suppress the error with null coalescing operator.
// Null coalescing operator
echo $value ?? '';
For the ancient PHP versions (< 7.0) isset() with ternary can be used
echo isset($value) ? $value : '';
Be aware though, that it's still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.
Suppress the error with the # operator. Left here for the historical reasons but seriously, it just shouldn't happen.
Note: It's strongly recommended to implement just point 1.
Notice: Undefined index / Undefined offset / Warning: Undefined array key
This notice/warning appears when you (or PHP) try to access an undefined index of an array.
Ways to deal with the issue are pretty much the same:
Recommended: Declare your array elements:
//Initializing a variable
$array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
echo $array['value']; // no error
Suppress the error with null coalescing operator":
echo $_POST['value'] ?? '';
With arrays this operator is more justified, because it can be used with outside variables you don't have control for. Therefore, consider using it for the outside variables only, such as $_POST / $_GET / $_SESSION or JSON input. While all internal arrays are best to be predefined/initialized first.
Better yet, validate all input, assign it to local variables, and use them all the way in the code. So every variable you're going to access deliberately exists.
Related:
Notice: Undefined variable
Notice: Undefined Index
Try these
Q1: this notice means $varname is not
defined at current scope of the
script.
Q2: Use of isset(), empty() conditions before using any suspicious variable works well.
// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';
// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
$user_name = $_SESSION['user_name'];
}
Or, as a quick and dirty solution:
// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);
Note about sessions:
When using sessions, session_start(); is required to be placed inside all files using sessions.
http://php.net/manual/en/features.sessions.php
Error display # operator
For undesired and redundant notices, one could use the dedicated # operator to »hide« undefined variable/index messages.
$var = #($_GET["optional_param"]);
This is usually discouraged. Newcomers tend to way overuse it.
It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.
There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect #-hidden notices with: set_error_handler("var_dump");
Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.
Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add # or isset only after verifying functionality.
Fix the cause first. Not the notices.
# is mainly acceptable for $_GET/$_POST input parameters, specifically if they're optional.
And since this covers the majority of such questions, let's expand on the most common causes:
$_GET / $_POST / $_REQUEST undefined input
First thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Is this an expected key name and present on each page request?
Variable names and array indicies are case-sensitive in PHP.
Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:
var_dump($_GET);
var_dump($_POST);
//print_r($_REQUEST);
Both will reveal if your script was invoked with the right or any parameters at all.
Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:
POST parameters and GET input will be be shown separately.
For $_GET parameters you can also peek at the QUERY_STRING in
print_r($_SERVER);
PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well.
You can also look at supplied raw $_COOKIES and other HTTP request headers that way.
More obviously look at your browser address bar for GET parameters:
http://example.org/script.php?id=5&sort=desc
The name=value pairs after the ? question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"] and $_GET["sort"].
Finally check your <form> and <input> declarations, if you expect a parameter but receive none.
Ensure each required input has an <input name=FOO>
The id= or title= attribute does not suffice.
A method=POST form ought to populate $_POST.
Whereas a method=GET (or leaving it out) would yield $_GET variables.
It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.
With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_REQUEST['vars'] again, which mashes GET and POST params.
If you are employing mod_rewrite, then you should check both the access.log as well as enable the RewriteLog to figure out absent parameters.
$_FILES
The same sanity checks apply to file uploads and $_FILES["formname"].
Moreover check for enctype=multipart/form-data
As well as method=POST in your <form> declaration.
See also: PHP Undefined index error $_FILES?
$_COOKIE
The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.
Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.
Generally because of "bad programming", and a possibility for mistakes now or later.
If it's a mistake, make a proper assignment to the variable first: $varname=0;
If it really is only defined sometimes, test for it: if (isset($varname)), before using it
If it's because you spelled it wrong, just correct that
Maybe even turn of the warnings in you PHP-settings
It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.
I didn't want to disable notice because it's helpful, but I wanted to avoid too much typing.
My solution was this function:
function ifexists($varname)
{
return(isset($$varname) ? $varname : null);
}
So if I want to reference to $name and echo if exists, I simply write:
<?= ifexists('name') ?>
For array elements:
function ifexistsidx($var,$index)
{
return(isset($var[$index]) ? $var[$index] : null);
}
In a page if I want to refer to $_REQUEST['name']:
<?= ifexistsidx($_REQUEST, 'name') ?>
It’s because the variable '$user_location' is not getting defined. If you are using any if loop inside, which you are declaring the '$user_location' variable, then you must also have an else loop and define the same. For example:
$a = 10;
if($a == 5) {
$user_location = 'Paris';
}
else {
}
echo $user_location;
The above code will create an error as the if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:
$a = 10;
if($a == 5) {
$user_location='Paris';
}
else {
$user_location='SOMETHING OR BLANK';
}
echo $user_location;
The best way for getting the input string is:
$value = filter_input(INPUT_POST, 'value');
This one-liner is almost equivalent to:
if (!isset($_POST['value'])) {
$value = null;
} elseif (is_array($_POST['value'])) {
$value = false;
} else {
$value = $_POST['value'];
}
If you absolutely want a string value, just like:
$value = (string)filter_input(INPUT_POST, 'value');
In reply to ""Why do they appear all of a sudden? I used to use this script for years and I've never had any problem."
It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.
The other critical setting is the errors can be hidden (i.e. display_errors set to "off" or "syslog").
What will have happened in this case is that either the error_reporting was changed to also show notices (as per examples) and/or that the settings were changed to display_errors on screen (as opposed to suppressing them/logging them).
Why have they changed?
The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.
However it is also possible to override these settings in
.htconf (webserver configuration, including vhosts and sub-configurations)*
.htaccess
in php code itself
and any of these could also have been changed.
There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.
(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)
Summary
Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.
Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed
Check error_reporting and display_errors php directives in .htaccess have not changed
If you have directive in .htaccess, check if they are still permitted in the .htconf file
Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.
The quick fix is to assign your variable to null at the top of your code:
$user_location = null;
Why is this happening?
Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is E_STRICT, which became turned on by default as of PHP 5.4.0.
Furthermore, according to PHP documentation, by default, E_NOTICE is disabled in file php.ini. PHP documentation recommends turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.
; Common Values:
; E_ALL (Show all errors, warnings and notices including coding standards.)
; E_ALL & ~E_NOTICE (Show all errors, except for notices)
; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
Notice that error_reporting is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.
To answer your question, however, this error pops up now when it did not pop up before because:
You installed PHP and the new default settings are somewhat poorly documented but do not exclude E_NOTICE.
E_NOTICE warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keeping E_NOTICE enabled forced me to declare my variables. It made it a LOT easier to learn C. In C, not declaring variables is much bigger of a nuisance.
What can I do about it?
Turn off E_NOTICE by copying the "Default value" E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED and replacing it with what is currently uncommented after the equals sign in error_reporting =. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini file. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.
Turn off E_NOTICE on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache 2, Nginx, or whatever your server of choice is. In Apache, you would use php_value inside of <Directory>.
Rewrite your code to be cleaner. If you need to do this while moving to a production environment or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see display_errors and log_errors in php.ini and your server settings).
To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of ~E_STRICT and ~E_DEPRECATED to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.
What do the errors mean?
Undefined variable: my_variable_name - This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future and makes it easier to read/learn the code.
function foo()
{
$my_variable_name = '';
//....
if ($my_variable_name) {
// perform some logic
}
}
Undefined index: my_index - This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.
// verbose way - generally better
if (isset($my_array['my_index'])) {
echo "My index value is: " . $my_array['my_index'];
}
// non-verbose ternary example - I use this sometimes for small rules.
$my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
echo "My index value is: " . $my_index_val;
Another option is to declare an empty array at the top of your function. This is not always possible.
$my_array = array(
'my_index' => ''
);
//...
$my_array['my_index'] = 'new string';
(Additional tip)
When I was encountering these and other issues, I used NetBeanss IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).
I used to curse this error, but it can be helpful to remind you to escape user input.
For instance, if you thought this was clever, shorthand code:
// Echo whatever the hell this is
<?=$_POST['something']?>
...Think again! A better solution is:
// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>
(I use a custom html() function to escape characters, your mileage may vary)
In PHP 7.0 it's now possible to use the null coalescing operator:
echo "My index value is: " . ($my_array["my_index"] ?? '');
Is equals to:
echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');
PHP manual PHP 7.0
I use my own useful function, exst(), all time which automatically declares variables.
Your code will be -
$greeting = "Hello, " . exst($user_name, 'Visitor') . " from " . exst($user_location);
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* #param mixed $var
* #param mixed $default
*
* #return mixed
*/
function exst(& $var, $default = "")
{
$t = "";
if (!isset($var) || !$var) {
if (isset($default) && $default != "")
$t = $default;
}
else {
$t = $var;
}
if (is_string($t))
$t = trim($t);
return $t;
}
In a very simple language:
The mistake is you are using a variable $user_location which is not defined by you earlier, and it doesn't have any value. So I recommend you to please declare this variable before using it. For example: $user_location = '';Or $user_location = 'Los Angles';
This is a very common error you can face. So don't worry; just declare the variable and enjoy coding.
Keep things simple:
<?php
error_reporting(E_ALL); // Making sure all notices are on
function idxVal(&$var, $default = null) {
return empty($var) ? $var = $default : $var;
}
echo idxVal($arr['test']); // Returns null without any notice
echo idxVal($arr['hey ho'], 'yo'); // Returns yo and assigns it to the array index. Nice
?>
An undefined index means in an array you requested for an unavailable array index. For example,
<?php
$newArray[] = {1, 2, 3, 4, 5};
print_r($newArray[5]);
?>
An undefined variable means you have used completely not an existing variable or which is not defined or initialized by that name. For example,
<?php print_r($myvar); ?>
An undefined offset means in an array you have asked for a nonexisting key. And the solution for this is to check before use:
php> echo array_key_exists(1, $myarray);
Regarding this part of the question:
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
No definite answers but here are a some possible explanations of why settings can 'suddenly' change:
You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.
You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)
You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.
Usually notices don't get displayed / reported (see PHP manual)
so it is possible that when setting up the server, the php.ini file could not be loaded for some reason (file permissions??) and you were on the default settings. Later on, the 'bug' has been solved (by accident) and now it CAN load the correct php.ini file with the error_reporting set to show notices.
Using a ternary operator is simple, readable, and clean:
Pre PHP 7
Assign a variable to the value of another variable if it's set, else assign null (or whatever default value you need):
$newVariable = isset($thePotentialData) ? $thePotentialData : null;
PHP 7+
The same except using the null coalescing operator. There's no longer a need to call isset() as this is built in, and no need to provide the variable to return as it's assumed to return the value of the variable being checked:
$newVariable = $thePotentialData ?? null;
Both will stop the Notices from the OP's question, and both are the exact equivalent of:
if (isset($thePotentialData)) {
$newVariable = $thePotentialData;
} else {
$newVariable = null;
}
If you don't require setting a new variable then you can directly use the ternary operator's returned value, such as with echo, function arguments, etc.:
Echo:
echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';
Function:
$foreName = getForeName(isset($userId) ? $userId : null);
function getForeName($userId)
{
if ($userId === null) {
// Etc
}
}
The above will work just the same with arrays, including sessions, etc., replacing the variable being checked with e.g.:
$_SESSION['checkMe']
Or however many levels deep you need, e.g.:
$clients['personal']['address']['postcode']
Suppression:
It is possible to suppress the PHP Notices with # or reduce your error reporting level, but it does not fix the problem. It simply stops it being reported in the error log. This means that your code still tried to use a variable that was not set, which may or may not mean something doesn't work as intended - depending on how crucial the missing value is.
You should really be checking for this issue and handling it appropriately, either serving a different message, or even just returning a null value for everything else to identify the precise state.
If you just care about the Notice not being in the error log, then as an option you could simply ignore the error log.
If working with classes you need to make sure you reference member variables using $this:
class Person
{
protected $firstName;
protected $lastName;
public function setFullName($first, $last)
{
// Correct
$this->firstName = $first;
// Incorrect
$lastName = $last;
// Incorrect
$this->$lastName = $last;
}
}
Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.
I.e.:
$query = "SELECT col1 FROM table WHERE col_x = ?";
Then trying to access more columns/rows inside a loop.
I.e.:
print_r($row['col1']);
print_r($row['col2']); // undefined index thrown
or in a while loop:
while( $row = fetching_function($query) ) {
echo $row['col1'];
echo "<br>";
echo $row['col2']; // undefined index thrown
echo "<br>";
echo $row['col3']; // undefined index thrown
}
Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.
Consult the followning Q&A's on Stack:
Are table names in MySQL case sensitive?
mysql case sensitive table names in queries
MySql - Case Sensitive issue of tables in different server
One common cause of a variable not existing after an HTML form has been submitted is the form element is not contained within a <form> tag:
Example: Element not contained within the <form>
<form action="example.php" method="post">
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
Example: Element now contained within the <form>
<form action="example.php" method="post">
<select name="choice">
<option value="choice1">choice 1</option>
<option value="choice2">choice 2</option>
<option value="choice3">choice 3</option>
<option value="choice4">choice 4</option>
</select>
<p>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</p>
</form>
These errors occur whenever we are using a variable that is not set.
The best way to deal with these is set error reporting on while development.
To set error reporting on:
ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);
On production servers, error reporting is off, therefore, we do not get these errors.
On the development server, however, we can set error reporting on.
To get rid of this error, we see the following example:
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
We can initialize the variables to NULL before assigning their values or using them.
So, we can modify the code as:
$test = NULL;
if ($my == 9) {
$test = 'yes'; // Will produce an error as $my is not 9.
}
echo $test;
This will not disturb any program logic and will not produce a Notice even if $test does not have a value.
So, basically, it’s always better to set error reporting ON for development.
And fix all the errors.
And on production, error reporting should be set to off.
I asked a question about this and I was referred to this post with the message:
This question already has an answer here:
“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
Undefined offset” using PHP
I am sharing my question and solution here:
This is the error:
Line 154 is the problem. This is what I have in line 154:
153 foreach($cities as $key => $city){
154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
I think the problem is that I am writing if conditions for the variable $city, which is not the key but the value in $key => $city. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?
UPDATE 1: The problem is that when executing $citiesCounterArray[$key], sometimes the $key corresponds to a key that does not exist in the $citiesCounterArray array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if $key exists in the array, then run the code, otherwise, skip it.
UPDATE 2: This is how I fixed it by using array_key_exists():
foreach($cities as $key => $city){
if(array_key_exists($key, $citiesCounterArray)){
if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
Probably you were using an old PHP version until and now upgraded PHP that’s the reason it was working without any error till now from years.
Until PHP 4 there was no error if you are using variable without defining it but as of PHP 5 onwards it throws errors for codes like mentioned in question.
If you are sending data to an API, simply use isset():
if(isset($_POST['param'])){
$param = $_POST['param'];
} else {
# Do something else
}
If it is an error is because of a session, make sure you have started the session properly.
Those notices are because you don't have the used variable defined and my_index key was not present into $my_array variable.
Those notices were triggered every time, because your code is not correct, but probably you didn't have the reporting of notices on.
Solve the bugs:
$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;
if(isset($my_array["my_index"])){
echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
}
Another way to get this out:
ini_set("error_reporting", false)
When dealing with files, a proper enctype and a POST method are required, which will trigger an undefined index notice if either are not included in the form.
The manual states the following basic syntax:
HTML
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Reference:
POST method uploads
In PHP you need first to define the variable. After that you can use it.
We can check if a variable is defined or not in a very efficient way!
// If you only want to check variable has value and value has true and false value.
// But variable must be defined first.
if($my_variable_name){
}
// If you want to check if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){
}
Simple Explanation
// It will work with: true, false, and NULL
$defineVariable = false;
if($defineVariable){
echo "true";
}else{
echo "false";
}
// It will check if the variable is defined or not and if the variable has a null value.
if(isset($unDefineVariable)){
echo "true";
}else{
echo "false";
}

Categories

Resources