In my code I use a php variable to display errors, such as
<span class="error"><?php echo $emailError; ?></span>
I only define the variable when there is an error to fill it with, so now XAMPP displays this error
Notice: Undefined variable: emailError
Its only a notice, so when deploying the code I would disable notices, or I could define everything before to make it go away.
$emailError = "";
$usernameError = "";
$firstnameError = "";
$lastnameError = "";
$languageError = "";
$passwordError = "";
$username = "";
$firstname = "";
$lastname = "";
$email = "";
But I find it weird to see something like this in my code, so my question is. Is it bad practice to only assign variables when needed, but always try to display them?
Yes, it is a bad practice. Initializing it to the empty string like you have shown is the best solution. Alternatively you could use the null coalescing operator like this:
<?php echo $emailError ?? ''; ?>
Although you need to do that every time you're not sure it's defined, so it's better just to initialize it like you have done.
As #Jeff pointed out, you might not want to have the span at all if there was no error in which case you should do something like this:
<?php if ( ! empty($emailError) ) { ?>
<span class="error"><?php echo $emailError; ?></span>
<?php } ?>
It is considered bad practice because it increases the chances of errors. I, however, use undeclared variables all the time, since it makes the code shorter, and if you are used to it, there is no problem.
Of course, your php settings need to be set to warn you (not) about undeclared variables. You can use error_reporting(...) to do that in php itself (on the go).
In the end it is just up to you. If you are a beginner, I encourage you to initialise all your variables and enjoy the blessings of the E_STRICT warnings to debug your code much more easily. Because you will not be the first one to be looking for three hours why $place = $p1ace / 2 ; doesn't work.
Related
While coding, i sometimes make the error of writing a single = instead of == in an if-statement. So lets say i have this:
<?php
$name = 'piet';
if($name == 'jan'){
print 'hello jan';
}
?>
And i make a mistake and write this instead:
<?php
$name = 'piet';
if($name = 'jan'){
print 'hello jan';
}
?>
This won't throw an error of course, since it is valid php code. However, i never use this short-hand notation, so if i enter it by mistake it will break the logic of my code without telling me why. Is there a solution for this? I am using aptana which is an editor based on eclipse. Is there any way i can add my own custom errors to an editor (or php) based on for example regular expressions? Or are there any other approaches to alert me whenever i make this mistake?
Just change the order to this:
if('jan' == $name) {
This is known under Yoda conditions:
So if you now make the mistake:
if('jan' = $name) {
This will give you an error!
I am writing some code to create fields automatically, which will save me a load of time. I have got most of my code working, but I have came across one error with the code, which is preventing me from achieving my final goal.
The code is as follows:
while ($i <= $numFields) {
$type = "\$field{$i}_Data['type']";
$name = "\$field{$i}_Data['name']";
$placeholder = "\$field{$i}_Data['placeholder']";
$value = "\$field{$i}_Data['value']";
echo '<input type="'.$type.'" name="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'">';
$i++;
}
The $numFields variable is defined at the top of my script, and I have worked out that it is something to do with how I am setting the variables $type, $name etc.
The end result is to create inputs depending on properties set in variables at the top of the script, The only issue I am having is with the settings of the variables, as said above.
If any extra code/information is needed, feel free to ask.
Thank you.
NOTE - There is no physical PHP error, it's purely an error with this:
"\$field{$i}_Data['value']";
There are a few ways we could write this one out, but they are all extensions of variable expansion and/or variable-variables.
Basically, we just need to put the variable name in a string and then use that string as the variable (much like you're currently doing with $i inside the string):
$type = ${"field{$i}_Data"}['type'];
$name = ${"field{$i}_Data"}['name'];
// ...
However, if you don't mind an extra variable, this can be written more cleanly by saving it like so:
$data = ${"field{$i}_Data"};
$type = $data['type'];
$name = $data['name'];
// ...
I wasn't able to find a solid work-a-round yet for it so I thought I just might ask here.
My error.log says for a good reason
[error] [client xxx.xxx.xxx.xxx] PHP Notice: Undefined index: Variablename
Till now I got rid of it with using a if statement around it like
if (isset($var)) {
if ($var ... ) { ... }
}
But now I got a lil problem so I can't use this "wrap-around" like above easily.
the check_login(...) function will write $_SESSION Variables like ['loginattempts'] or ['captchaattempts'] - now I want to let the login disappear if those attemps reach a specified amount. Like
if ($_SESSION['loginatt'] < x && $_SESSION['capatt'] < x) { echo 'login form...';}
If I would wrap a check if the variable is set around it - the login wouldn't appear if those variables are not set.
Possible work-a-rounds could be
if (!isset($var)) {echo 'login form ...';}
else {echo 'login form...';}
but that would mean I would have to have a duplicate login form in my code
I know could also just change this echo 'login form ...' into a requice_once 'include/loginform.php' - but there would be still a duplicate entry for this require_once command.
I could also set a $testvar like
if (isset($var)) {
if ($var > x) {
echo 'acc. blocked;
$testvar = 0;
}
else {
$testvar = 1;
}
if ($testvar < 1) {
echo 'login form...';
}
So are there any other ways as those ?
If not which way you would suggest to take to keep the code as it should be for "good programming" ?
Any statements are welcome, thanks for helping out
Kris
In my experience, it's always a good idea to output all errors during development and to always have initialized values. It can get rid of some bugs as you will always have a default value to fall back on.
An easy way to fix your problem is to use another variable and to add your $_SESSION variables only if they exist. For instance:
$login_attempts = 0;
if (isset($_SESSION['loginattempts'])) {
$login_attempts = $_SESSION['loginattempts'];
}
Alternatively, a ternary expression is also possible for compactness, although with the long loginattempts index this looks a little harsh, in my opinion.
$login_attempts = (isset($_SESSION['loginattempts'])) ? $_SESSION['loginattempts'] : 0;
Start defining indexes!
you can directly check if session vars are set or not
if (isset ($_SESSION['loginatt'])) { /* action here */ }
if you want to reduce redundancy in use of login form string
you can declare it under a variable, like
$loginform = '<form action="" ...>';
$loginform .= '<input type='"...>';
and echo it anywhere you want.
Suppose that I have the PHP function as below:
function.php
<?php
function getDataInFile($PMTA_FILE){
$PMTA_DATE = date("Y-m-d");
$lineFromText = explode("\n", $PMTA_FILE);
$number_bar_charts = 13;
$row = 0;
$cate = "";
$total ="";
$fail = "";
$mailSuc = "";
$title = "";
foreach($lineFromText as $line){
if($row < $number_bar_charts){
$words = explode(";",$line);
$dateTime .= ','.$words[0];
if($title == ""){
$title = $words[0];
}
$cate .= ','."'$words[5]'";
$total .= ','.$words[6];
$fail .= ','.$words[7];
$mailSuc .= ','.((int)$words[6] - (int)$words[7]);
$row++;
}
}
}
?>
This is code below that I call the function to use in getFile.php.
<?php
include("include/function.php");
$PMTA_DATE = date("Y-m-d");
getDataInFile("../stats_domain_recepteur.affinitead.net.".$PMTA_DATE.".txt");
?>
In fact, it can not read data from the file, I got the error messages Undefined variable: dateTime in C:\wamp\www\chat\include\function.php on line 15,Notice: Undefined offset: 5 in C:\wamp\www\chat\include\function.php on line 19....
I do not know how to fix this, Anyone help me please, Thanks.
These are Notices only. They are not terrible errors that will blow up your code, but some code reviewers would make you fix them. PHP is just giving you a polite nudge, but will work anyhow. Fatal errors are the big, bad problems that will stop PHP in its tracks.
Here are the problems PHP found...
You're appending data to the string $dateTime on each iteration. On the first pass through the variable doesn't yet exist. PHP doesn't really care, but will issue a warning. To get rid of that problem, define $dateTime before you use it.
$dateTime = null;
The second problem is an array out of bounds exception. You are trying to do something with $words[5] when that array index doesn't exist. In general, you should check that array indexes, variables and other fun stuff actually exist before you try to use them.
$cate .= sprintf(",'%s'", isset($word[5]) ? $word[5] : '');
If you don't want to see Notices and Warnings reported in the error log, see PHP Error Handling to learn how to set which error levels you want to see in your log.
You should also read all about the file_get_contents function to actually get the file in the first place!
add $dateTime = ''; before foreach($lineFromText as $line){
this will works fine.
The error messages are 100% legit: you're trying to use a variable which hasn't been initialized before. Put this code above the loop and you'll get rid of this error:
$dateTime = '';
Regarding the second error - it tells that you don't have 6-th element in the array, so you'd better replace that code with a check:
$cate .= sprintf(",'%s'", isset($word[5]) ? $word[5] : '');
Extrapolate this check to other index accesses, as well.
<?php echo isset($areas['footer']) ? $areas['footer'] : null; ?>
Any way to improve that?
Note that you are echoing and in false condition it would be null which does not have any effect. You could say like 'empty' or ' ' or 'not found' instead. Other alternative is to get the return value of isset:
$return = isset($areas['footer']) ? $areas['footer'] : null;
if ($return)
{
// $return contains footer info
}
else
{
// footer was not set :(
}
Depending on where $areas comes from it might be cleaner to assign it to a variable:
$footer = isset($areas['footer']) ? $areas['footer'] : null;
Then you can use $footer without any additional isset checks.
You can also spare the else branch, by setting a default:
$footer = null;
if (isset($areas['footer'])) {
$footer = $areas['footer'];
}
echo $footer;
No, this is the most concise way of handling this sort of output.
"i'm using this kind of code very often"
Maybe you should avoid the issue altogether by using a template language, or encapsulating this behavior in a function?
like this:
function get_area($area) {
if... //your code
return $area
One shorter version i can think of would be:
<?php !isset($areas['footer']) or print $areas['footer']; ?>
But i'm not sure if it is faster or more elegant.
What do you guys think?
echo $areas['footer'];
Simple and has the exact same effect as the original line.
Edit in reply to Felix
This gives a notice, but unless you're supposed to turn this in as ultra-perfect homework, it doesn't really matter. You can either fill your code with isset calls or ignore small stuff like this. I'd worry about it if I was working in say... Java, but pragmatically nobody is going to care if PHP code that works produces notices.