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.
Related
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.
I'm trying to call this from string Yii::app()->user->id_rol. So, I want to take this string and do the call then.
I tried to do this:
$class = "Yii::app()->user->id_rol";
$class = explode('::',$class);
$class[1] = explode('->',$class[1]);
$class2 = new $class[0];
$string = "";
$n = count($class[1]);
for($i = 0; $i<$n;$i++){
(($i+1) == $n) ? $fl = '' : $fl = '->';
$string .= $class[1][$i].$fl;
}
$model = $class2->$string;
...but that doesn't work.
Undefined property: Yii::$app()->user->id_rol
How could I make it work?
I think mnv's comment above is the way to go. Otherwise you risk all sorts of problems with code injection and whatnot. In the worst case, if you really want to do this, I'd recommend doing the following (as much as it pains me to write this):
$code = "return {$VARIABLE_FROM_DB};";
$value = eval($code);
That said, there should be a better way to do what you are trying to do overall. What is the source of the DB provided code? Can you reformat it in a way that you are not saving code into the database?
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'];
// ...
The code below is more or less a chunk of my code. The $servername and $monthlyincome variables are not actually static as shown here but I changed them so I could add less code here.
If I run this code...
$servername="Server1";
$months = array('January','February','March','April','May','June','July','August','September','October','November','December');
for ($i=0;$i<=24;$i++) {
$new_time = mktime(0,0,0,date("m")+$i,1,date("Y"));
$months_array[date("Y",$new_time)][date("m",$new_time)] = "x";
}
$overallincome = 0;
foreach ($months_array AS $year=>$month) {
foreach ($month AS $mon=>$x) {
$monthlyincome = 3;
$overallincome += $monthlyincome;
$$servername[$months[$mon-1]." ".$year]['monthlyincome']=$monthlyincome;
$$servername[$months[$mon-1]." ".$year]['overallincome']=$overallincome;
}
}
I get this error...
Cannot use string offset as an array in on line 123
Line 123 is this line... $$servername[$months[$mon-1]." ".$year]['monthlyincome']=$monthlyincome;
I can't figure out what I am doing wrong. I have checked other posts on SO with the same error but nothing made sense to me.
Putting it as an answer, then!
$$servername[] seems to be the problem. It's interpreting it as ${$servername[]} where you want it to interpret as ${$servername}[].
Try putting those curly-brackets in there and see if that helps.
I'm trying to parse a 6,000 line 500 KB file into an array so I can import the data into our system. The problem is that the script stops executing somewhere between lines 3000-4000. There are no breaks in the code, we use it on other imports. Any ideas on why this might be happening and what I can do to prevent it?
/**
* Takes a seperated value string and makes it an array
* #param $delimiter string The delimiter to be seperated by, usually a comma or tab
* #param $string string The string to seperate
* #return array The resulting array
*/
public function svToArray ($delimiter, $string) {
$x = 0;
$rowList = array();
$splitContent = preg_split("#\n+#", trim($string));
foreach ($splitContent as $key => $value) {
$newData = preg_split("#".$delimiter."#", $value);
if ($x == 0) {
$headerValues = array_values($newData);
} else {
$tempRow = array();
foreach ($newData as $rowColumnKey => $rowColumnValue) {
$tempRow[$headerValues[$rowColumnKey]] = $rowColumnValue;
}
$rowList[] = $tempRow;
}
$x++;
}
return $rowList;
}
UPDATE:
Error reporting is enabled. I've started using a file that's only 130KB at 1,500 lines and it does the same thing...
When I add debug code as in the following example nothing echoes at all unless I put an exit after the echo "test<br/>";
public function svToArray ($delimiter, $string) {
$x = 0;
$rowList = array();
$splitContent = preg_split("#\n+#", trim($string));
echo "test<br/>";
foreach ($splitContent as $key => $value) {
$newData = preg_split("#".$delimiter."#", $value);
if ($x == 0) {
$headerValues = array_values($newData);
} else {
$tempRow = array();
foreach ($newData as $rowColumnKey => $rowColumnValue) {
$tempRow[$headerValues[$rowColumnKey]] = $rowColumnValue;
}
$rowList[] = $tempRow;
}
$x++;
}
echo "test";
$this->tru->debug($rowList);
exit;
return $rowList;
}
UPDATE
If I comment out $tempRow[] = $rowColumnValue; then it echoes everything fine....
Probably it just timeouts. Does it always stop after X seconds?
Try setting the max execution time higher: set_time_limit(900) at the top of your pages.
You can check the max execution time in your phpinfo():
1. Create a new php page with
2. Search for max_execution_time
Have you looked at the files? Is there a line with too many delimiters? Also, what are all the "#" about?
My best guess is that you're hitting a line where $headerValues[$rowColumnKey] is not defined.
What about $rowColumnKey and $rowColumnValue ?
They are not defined in the function.
Make sure that you have error reporting set, put this on top of your php file:
ini_set('display_errors', true);
error_reporting(E_ALL);
Also you can extend the script's execution time:
ini_set('max_execution_time', 50000);
About the only time I've a php script die, with no output and no errors is when it runs out of memory. It doesn't look like your script would use much memory, but I would check to make sure that the memory limit for php is high enough.
Are you sure that you are iterating through the returned array instead of simply trying to print it? (The issue may be outside of the function rather than within it.)
Also...
`exit;
return $rowList;`
Try removing the 'exit;' line and see if that changes anything.
Also, $splitContent is not defined as an array before being used, but preg_split is going to return an array. (This should not impact your results, but it is safe to do so.)
Why are you using $key => $value pairs when you cannot be sure of what will be within the string? If we could see an small example of the content of $string, we might be able to adjust this function to work better.
The # should be replaced with /, but that may simply be a formatting issue.
$newData should be defined as an array before being used just to be safe even though that is not causing your issue.
If you can, increase maximum execution time in php.ini.. also increase the maximum memory amount for each instance.. checking error logs of your webserver could also help.
It appears as though there was too much output to the output buffer, causing the page to show nothing at all.