简体   繁体   中英

using C to generate simple html page with cgi

C program:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *data = getenv("QUERY_STRING");
    char userName[30];
    sscanf(data,"uname=%s", userName);
    printf ("Content-Type: text/html\n\n");
    printf ("<html>");
    printf ("<head> </head>");
    printf ("<body>");
    printf ("<h2 style=""text-align:center;color=red"";> %s </h2>", userName);
    printf ("</body> </html>");
    return 0;
}

HTML:

<!doctype html>

<html lang="en">

<head>

</head>

<body>
    <form action="echo.cgi" method="get">
        Please enter your name: <input type="text" name="uname">  <br> 
        <input type="submit" value="Submit">
    </form>
</body>

</html>

I am trying to use the C program to make a simple html page that just displays the variable uname with GET from html. I am trying to do this by first compiling C to CGI with:

gcc echo.c -o echo.cgi

which it does fine. However, whenever I press submit the cgi file just starts to download. What am I doing wrong

You have to run this through an HTTP server with CGI configured. Simply navigating your browser to your local HTML file on your disk isn't going to execute your code. The server will execute your code and return the output as the response.

Also, I want to point out CGI is a security risk. I realize this is probably just minimal sample code, but because you are not checking the bounds of your string before calling sscanf , you have a vulnerability that someone could exploit to gain access to your server. https://en.m.wikipedia.org/wiki/Buffer_overflow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM