Undefined variable: add_sub_catg_details while using #foreach [duplicate] - mysql
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";
}
Related
Ubuntu upgrade and Drupal 6 [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"; }
How do I debug lua functions called from conky?
I'm trying to add some lua functionality to my existing conky setup so that repetitive "code" in my conky text can be cleaned up. For example, I have information for each mounted FS, each core, etc. where each row displayed in my panel differs ONLY by one parameter. My first skeletal, attempt at using lua functions for this seems to run but displays nothing in my panel. I've only found very simple examples to base this on, so I may have made a simple error, but I don't even know how to diagnose it. My code here is modeled after what I HAVE been able to find regarding writing functions, such as this How to implement a basic Lua function in Conky? , but that's about all the depth I've found on the topic except for drawing and cairo examples. Here's the code added to my conky config, as well as the contents of my functions.lua file conky.config = { ... lua_load = '/home/conky-manager/MyConky/functions.lua', }; conky.text = [[ ... ${voffset 5}${lua conky_test 'test'} ... ]] file - functions.lua function conky_test(parm1) return 'result text' end What I would expect is to see is "result text" displayed in my panel at the location where that function call appears, but nothing shows. Is there a log created by conky as it runs, or a way to provide some debug output? Even if I'd made a simple error here, I'd still like to have the ability to diagnose things as my code gets more complex.
Success! After cobbling info from several articles together, I figured out my basic flaws - 1. Missing a 'conky_main' function, 2. Missing a 'lua_draw_hook_post' to invoke it, and 3. Realizing that if I invoke conky from a terminal, print statements in lua would appear there. So, for anyone who sees this question and has the same issues, here's the corrected code. conky.config = { ... lua_load = '/home/conky-manager/MyConky/functions.lua', lua_draw_hook_post = "main", }; conky.text = [[ ... ${lua conky_test 'test'} ... ]] and the proper basics in my functions.lua file function conky_test(parm1) return 'result text' end function conky_main() if conky_window == nil then return end end A few notes: I still haven't determined if using 'lua_draw_hook_pre' instead of 'lua_draw_hook_post' makes any difference, but it doesn't seem to in this example. Also, some examples showed actually calling this 'test' function instead of writing a 'main', but the 'main' seemed to have value in checking to see if conky_window existed. Some examples seemed to state that naming functions with the prefix 'conky_' was required, but then showed examples of calling those functions without the prefix, so I assume the prefix is inferred during the call.
a major note: you should run conky from the directory containing the lua scripts.
Understanding the use of Tcl namespace variable
I have a namespace variable which is defined as below: namespace eval ::SMB::{ variable SmbInfo ------ ------ proc ::SMB::SmbCreate {name dutport} { variable SmbInfo global DutPorts DutPort_2 DutPorts_3 smb ------ ------ if{"" != [info command SMB::$name]} { return -code error "command name \"$name\" already exists" } set SmbInfo($name -DutPort) $dutport I am new to Tcl and trying to understand the above piece of code. Few questions, please correct me if I am wrong at any point: The variable SmbInfo defined on top in namespace is getting overridden by the one declared in the procedure SmbCreate. I am unable to figure out what is the objective of the line: set SmbInfo($name -DutPort) $dutport I can see that 'DutPorts' is defined as global but I could not find 'DutPort'. I have not executed the code yet. Could it be an error? Is ($name - DutPort) creating an array index for the variable SmbInfo and the value of $dutport is being set to that particular array variable? I have similar code structures in the file like below set SmbInfo($name - SmbSetDmac) [BuildMac1 $SmbInfo($from_name-DutPort)] Where BuildMac1 is a procedure. A bit explanation of the above code might also make the thing clear. If anything I missed to post in the question, kindly point me, I will edit my question. Thanks in advance.
The second declaration doesn't override, it's the same variable in both cases. The command is a syntax error because of the space after $name. The intent seems to be to assign the value of $dutport to the member of SmbInfo that has the name "$name -DutPort" (where $name is replaced by the variable value). A similar assignment, but here the value comes from the result of the command. There are a few syntax errors in the code, too many or too few spaces here and there. It seems unlikely this code has ever been executed. The purpose of the smb::SmbCreate command would seem to be to 1) create a new command in the SMB namespace named by the first parameter (unless such a command already exists) and 2) store metadata in the SmbInfo namespace variable, indexed by a) the name parameter and b) a keyword such as -DutPort or -SmbSetDmac. Code like this essentially implements an ad-hoc object-oriented interface. If the whitespace issues are resolved, it should work fine.
You have many syntactic problems that are going to cause you much grief. Tcl cares very much about its syntax level, which includes exactly where the spaces and newlines are, and whether there are {braces} and [brackets] as expected. You must get these things right. Looking at the specific code you're having problems with, this line: set SmbInfo($name -DutPort) $dutport would appear to be highly unlikely, as it is passing three arguments to the set command when that only takes one or two. I'd guess that you've got a command that you're calling to obtain a key for an array, and that the code therefore ought to be this: set SmbInfo([$name -DutPort]) $dutport See those [brackets]? They matter here, as they say “run my contents as a little subscript and use the result”. With that sorted out, there's also the question of whether $name -DutPort works at all, but you'll just have to be guided by the error messages there. Tcl usually gives very good error messages, though sometimes you have to think about why the code got in the state where it is giving that message in order to figure out what the actual problem is. You know, usual debugging… I would expect similar problems with: set SmbInfo($name - SmbSetDmac) [BuildMac1 $SmbInfo($from_name-DutPort)] and would guess that it is actually supposed to be: set SmbInfo([$name -SmbSetDmac]) [BuildMac1 $SmbInfo([$from_name -DutPort])] Note again that I have modified the spaces to follow the existing pattern (which I'm guessing is a property access; it looks like it's OTcl or XOTcl) and added brackets. Finally, this line: if{"" != [info command SMB::$name]} { is also syntactically wrong, and should instead be: if {"" != [info command SMB::$name]} { That extra space matters, because it separates the word that is the command name (if) from the word that is the condition expression. The remainder of the line is probably correct (the SMB::$name might be suspicious, except you're using it in info command, but then you probably only need info command $name as it already knows about what namespace you're working in and you're using the unqualified name elsewhere).
Log In example with xQuery
I'm trying to create a function that allows me to evaluate the login credentials for a restricted area of a database. this is my code: declare function local:check() as xs:string { let $login := request:get-parameter("username",'') let $password := request:get-parameter("password",'') let $user := doc('credentials.xml')/credenziali/utente[./user = $login] return ( if (not(empty($user))) then concat('staff.xq',$login,' ',$password) else concat('login_error.xq',$login,' ',$password) ) }; This function is called in: form name="login" method="post" action="{local:check()}" but I can not understand why I am always redirected to the page ''login_error'' (ie the user object always empty) despite i enter correct credentials (available in the file credentials.xml). Credentials.xml contain: <credenziali> <utente id="1"> <user>admin</user> <password>admin</password> </utente> </credenziali> and i set, in the respective input text box of screen, username=admin and password=admin
Without more information it's hard to see exactly what the trouble is here. But we can reason about it. The software is telling you that $user is always empty. That means that doc('credentials.xml')/credenziali/utente[./user = $login] evaluates to the empty sequence. If it were my code, I'd now check the following: Does $login have a value? Is doc('credentials.xml') empty? If non-empty, does it have an outermost element named credenziali? If so, does credenziali have children (or: a child) named utente? If so, does utente have a child named user? (Why would an element named utente have a child named user, I ask myself. Shouldn't it be username or something? But, hey, it's your XML, not mine, you call things what you like. I'm just showing you that I'm paying attention.) If so, do any of the user elements have a string value which is identical to to the value of $login? If the answer to all of those questions is yes, then you have a really interesting and challenging issue, and perhaps a bug report for your XQuery engine. If I had to bet, without knowing anything more than I do, I'd bet on the first two questions -- because they involve interacting with the environment, which is (a) non-standardized, (b) often complicated by considerations that seem extraneous, (c) often very difficult for the library creator to document well (since they can't know everything they need to know about your environment), and so (d) often not documented particularly well, and thus (e) error prone. I find trial and error helps a lot. [postscript] You ask how to check to see whether $login and $user are being initialized correctly. There are no rules or limits here. Debugging XQuery is a lot like debugging any other programming language; you need to find ways to make what is going on in the code visible on your screen, so you can figure out where things are going wrong. Some possibilities: Temporarily replace the initialization of the variables with something like let $login := "Paolo", $password := "Francesca" $usersdoc := <credenziali> <utente id="1"> <user>Paolo</user> <password>Francesca</password> </utente> </credenziali> let $user := $usersdoc//utente[./user = $login] Make sure this works. (If it doesn't, your problem is somewhere else.) Then replace the initialization of $login with the original code and see if it still works. If it does, replace the initialization of $password and see if it still works. If it does, replace the initialization of $usersdoc, and then $user. Remove the conditional and return, unconditionally, some value that allows you to see the value of $login. (E.g. let $login := request:get-parameter("username",'') let $password := request:get-parameter("password",'') let $user := doc('credentials.xml') /credenziali/utente [./user = $login] return concat('staff.xq...',$login,'...',$password) I'm guessing that the string returned by your login function is the URI to which the user is going to be redirected -- if that's so, should you not have a slash or something between 'staff.xq' and the login id? If it's not the URI to which the user is being redirected, you may need to adjust things in the caller so you can see what values are being emitted for $login and $password. Use trace(), if your XQuery engine produces logs you can inspect.
Why does XML::LibXML keeps printing errors even when I disable them?
I'm using XML::LibXML to parse a document. The HTML file behind it, has some minor errors, and the parser reports them: http://is.gd/create.php?longurl=http://google.com:15: validity error : ID smallink already defined nal URL was http://google.com<span id="smallink" ^ http://is.gd/create.php?longurl=http://google.com:15: validity error : ID smallink already defined and use http://is.gd/fNqtL-<span id="smallink" ^ However, I disabled error reporting: my $parser = XML::LibXML->new(); $parser->set_options({ recover => 2, validation => 0, suppress_errors => 1, suppress_warnings => 1, pedantic_parser => 0, load_ext_dtd => 0, }); my $doc = $parser->parse_html_file("http://is.gd/create.php?longurl=$url"); My only option to suppress those errors, is to run the script with 2>/dev/null, which I don't want. Could someone help me please get rid of those errors?
I have no idea if you're asking XML::LibXML corretly to not print its warnings. I'll assume you are and this is a bug in XML::LibXML (which you should also report to the author), and only address how to suppress warnings. Every time a warning is about to be printed, perl will look up the value of $SIG{__WARN__} and, if that contains a code reference, invoke it instead of printing the warning itself. You can use that stop the warnings you want to ignore to be printed to STDERR. However, you should be careful with this. Make sure to only suppress false-positives, not all warnings. Warnings are usually useful. Also, make sure to localize your use of $SIG{__WARN__} to the smallest possible scope to avoid odd side effects. # warnings happen just as always my $parser = ...; $parser->set_options(...); { # in this scope we filter some warnings local $SIG{__WARN__} = sub { my ($warning) = #_; print STDERR $warning if $warning !~ /validity error/; }; $parser->parse_html_file(...); } # more code, now the warnings are back to normal again Also note that this is all assuming those warnings come from perl-space. It's quite possible that libxml2, the C library XML::LibXML uses under the hood, writes warnings directly to stderr itself. $SIG{__WARN__} will not be able to prevent it from doing that.
A possible solution is to install a $SIG{__WARN__} handler which filters the messages or just silences all warnings: local $SIG{__WARN__} = sub { /* $_[0] is the message */ };