I am trying to make my code more efficient by creating a function to hold code that is repeated.
Old code (that works):
// this block appends the file with a single line of all the responses in the same order as the variable list (hopefully)
if($fp = fopen("reg.txt", "ab")) { // open the file appending in binary mode
$j = 0; // counter set to zero
foreach($_POST as $i => $val) { // foreach loop in form elements, each arry element name is set to $i, its value set to $val
if( $j != count($_POST) - 1 ) // if we are not on the last element of the arry,
fwrite($fp, $val."\t"); // write data with a tab
else // if we ~are~ on the last element of the array,
fwrite($fp, $val."\n"); // write data with a new line
$j = $j + 1; // increment the counter
}
fclose($fp); // close the file
So I took out the bit that would be repeated and created this function:
function filewrite() {
$j = 0; // counter for the foreach command, since foreach uses the array's native element names and not a number
foreach($_POST as $i => $val) { // foreach loop in form elements, each array element name is set to $i, its value set to $val
if( $j != count($_POST) - 1 ) // if we are not on the last element of the array,
fwrite($fp, $i."\t"); // write data with a tab
else // if we ~are~ on the last element of the array,
fwrite($fp, $i."\n"); // write data with a new line
$j = $j + 1; // increment the counter
}
fclose($fp); // close the file
}
Using this function gets this error: Warning: fwrite(): supplied argument is not a valid stream resource in ... line 19
Line 19: fwrite($fp, $i."\t"); // write data with a tab
When I look at solutions to this error message, all I get is the chmod setting is wrong. However, the old code worked with the present security setup. So what is really causing the error?
Thank you.