Undefined index with $_POST
In PHP, a variable or array element which has never been set is different from one whose value is null
; attempting to access such an unset value is a runtime error.
That's what you're running into: the array $_POST
does not have any element at the key "username"
, so the interpreter aborts your program before it ever gets to the nullity test.
Fortunately, you can test for the existence of a variable or array element without actually trying to access it; that's what the special operator isset
does:
if (isset($_POST["username"]))
{
$user = $_POST["username"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
This looks like it will blow up in exactly the same way as your code, when PHP tries to get the value of $_POST["username"]
to pass as an argument to the function isset()
. However, isset()
is not really a function at all, but special syntax recognized before the evaluation stage, so the PHP interpreter checks for the existence of the value without actually trying to retrieve it.
It's also worth mentioning that as runtime errors go, a missing array element is considered a minor one (assigned the E_NOTICE
level). If you change the error_reporting
level so that notices are ignored, your original code will actually work as written, with the attempted array access returning null
. But that's considered bad practice, especially for production code.
Side note: PHP does string interpolation, so the echo
statements in the if
block can be combined into one:
echo "$user is your username";
Undefined index for $_GET
The problem is that you don't propagate the $code
variable to when the button submit is clicked. To fix it, just add ?code=
to your action
form:
<?php $code = isset($_GET['code']) ? $_GET['code'] : ""; ?>
<form method="post" id="contact_form" action="feedback_form_entry.php?code=<?php echo $code; ?>">
php $_GET and undefined index
Error reporting will have not included notices on the previous server which is why you haven't seen the errors.
You should be checking whether the index s
actually exists in the $_GET
array before attempting to use it.
Something like this would be suffice:
if (isset($_GET['s'])) {
if ($_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
else if ($_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
else if ($_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
} else {
echo "<body>";
}
It may be beneficial (if you plan on adding more cases) to use a switch
statement to make your code more readable.
switch ((isset($_GET['s']) ? $_GET['s'] : '')) {
case 'jwshxnsyllabus':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
break;
case 'aquinas':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
break;
case 'POP2':
echo "<body onload=\"loadSyllabi('POP2')\">";
break;
default:
echo "<body>";
break;
}
EDIT: BTW, the first set of code I wrote mimics what yours is meant to do in it's entirety. Is the expected outcome of an unexpected value in ?s=
meant to output no <body>
tag or was this an oversight? Note that the switch will fix this by always defaulting to <body>
.
Notice: Undefined variable, Notice: Undefined index, Warning: Undefined array key, and Notice: Undefined offset using PHP
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 errorSuppress 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 errorSuppress 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
Related Topics
Phpmailer Error: Smtp -> Error: Failed to Connect to Server
Routes in Codeigniter - Automatically
Call to Undefined Function Password_Hash()
How to Attach an Image Using PHPmailer
How Do We Implement Custom API-Only Authentication in Laravel
How to Join Three Tables in Codeigniter
Laravel Input Facade VS Request Facade
Imagick Not Loading Images, with 'Nodecodedelegateforthisimageformat' Error Message
How to Detect Ambiguous and Invalid Datetime in PHP
How to 'JSON_Encode()' Keys from PHP Array
PHP Upload Size and Its Impact on Post Size and Memory Limit
Properly Escaping with MySQLi | Query Over Prepared Statements
Convert Hex to Ascii Characters
Php's Function to List All Objects's Properties and Methods