Description : Use C language to design a web counter based on CGI-BIN.
It is required to open the webpage from multiple computers and refresh, the counter can be accumulated normally; the value of the counter needs to be persistently stored, that is, it will not start from the initial value every time. That is, when the web page is refreshed once, the count increases by one .
Here, persistent storage is achieved through file reading and writing .
Condition : Apache is installed and configured
Implementation :
1. Create a new count.c file in the /var/www/cgi-bin directory and enter the following code
#include<stdio.h>
int main()
{
printf("Content-type:text/html\n\n");
printf("<html>\n");
printf("<head><title>An html page from a cgi</title></head>\n");
printf("<body bgcolor=\"#E6E6FA\"></body>\n");
printf("</html>\n");
fflush(stdout);
FILE *fp = NULL;
int num;
fp = fopen("test.txt", "r");
fscanf(fp,"%d",&num);
fclose(fp);
printf("A simple amount counter:\n");
printf("%d",num);
fp = fopen("test.txt", "w");
num++;
fprintf(fp, "%d",num);
fclose(fp);
}
2. Create a new test.txt file in the same directory, enter 0 as the initial value of the count, and set the file attributes
sudo chmod 666 test.txt
3. Enter the following code
sudo gcc -o count.cgi count.c
4. Open localhost/cgi-bin/count.cgi in the browser to achieve the above functions, refresh the webpage once the count is increased by 1, and close the webpage and reopen the count as the count result before the end of the last time +1, enter
localhost under the same ip /cgi-bin/count.cgi can use the web counter