I want to create an image Counter. Why does my code report an error? follow the video to learn the following: & nbsp; what is the foreshadowing before the image counter, Text Counter & lt ;? Php & nbsp; if & nbsp ;(! @ $ F = fopen ("num.txt", & nbsp; "r") {echo & nbsp; "file does not exist"; $ num = 0 ;} why does my code report an error when else & nbsp; wants to create an image counter?
Follow video learning
The following describes the preparation of the image counter and the text counter.
If (! @ $ F = fopen ("num.txt", "r ")){
Echo "the file does not exist ";
$ Num = 0;
} Else {
Fgets ($ f, 10 );
Fclose ($ f );
}
$ Num ++;
$ Ff = fopen ("num.txt", "w ");
Fwrite ($ ff, $ num );
Fclose ($ ff );
Echo $ num;
?>
------------------------------------------------
The first normal operation, you can create a new num.txt file, and the counter jumps to 1
However, if you run it again, the number 2 should be displayed.
But it is shown as follows:
(! ) SCREAM: Error suppression ignored
(! ) Notice: Undefined variable: num in C: \ wamp \ www \ PHP100 \ PHP07-GraphicalCounter.php on line 42
Call Stack
# TimeMemoryFunctionLocation
10.0006253472 {main} () .. \ PHP07-GraphicalCounter.php: 0
1
------ Solution --------------------
Use the file_exists function to determine whether a file exists.
Does not exist: create a file and write 1
Yes: open the file, read the file content, add 1, and write
------ Solution --------------------
If (! @ $ F = fopen ("num.txt", "r ")){
Echo "the file does not exist ";
$ Num = 0;
} Else {
$ Num = fgets ($ f, 10 );
Fclose ($ f );
}
$ Num ++;
$ Ff = fopen ("num.txt", "w ");
Fwrite ($ ff, $ num );
Fclose ($ ff );
Echo $ num;
------ Solution --------------------
Using filename='num.txt ';
If (file_exists ($ filename )){
// File exists
$ F = fopen ($ filename, 'R + ');
$ Num = (int) fgets ($ f );
$ Num ++;
Rewind ($ f );
} Else {
// The file does not exist.
$ F = fopen ($ filename, 'w ');
$ Num = 1;
}
Fputs ($ f, $ num );
Echo 'You are the '. $ num.' person accessing the page ';
Fclose ($ f );