Page 1

Web Programming Using C/C++ (Setting up example project, Source code of API, Tutorial on using API, API Reference) (THIS FILE BELONGS TO THE ZIP FILE CONTAINING C API and EXAMPLE PROJECT, IF YOU DON’T HAVE THEM, VISIT THE BLOG LINK BELOW TO DOWNLOAD)

By Sriram.A.S. Originally posted in:

NOTE This guide/API is NOT for programmers or people who are working with real time data, as the API is not yet tested thoroughly. This project is targeted on people who are mainly of non-computer origin and wish to do some SIMPLE web app in C/C++. Mainly, this is for non computer tech people who need a bit of web app for presenting their project, thesis etc., THIS API IS TESTED WITH BORLAND C++ COMPILER, WINDOWS AND APACHE

DOWNLOADS Make sure that you have the header file web.h which comes with this document and the example directory which contains a simple small example of this API with C. Also, in order to run the programs, you need a C compiler, in this tutorial, I have given the link for Borland C/C++ Compiler. Also in order to run a web app, we need a web server, don’t worry much about the complexities, a link to Apache web server is given with this link. Download the following files: 1. Borland C/C++ Compiler 5.5 ols.exe 2. Apache HTTP server Download any file Stable Release, Beta Release, anything, click the version there and then the page moves down to a list of builds, select Win32 Binary without crypto, file looks like httpd-2.2.21-win32-x86-no_ssl.msi. The version numbers might change.

3. Make sure you have web.h and the example directory, which comes with this zip file. Or else download from my blog (link given in 1 st page) If you face any problems in downloading the required files, email me, I will help you. Also, this guide doesn’t speak about linux, if you face any problems, Email me!

PROJECT SETUP IN WINDOWS (VERY SIMPLIFIED) 1. Install Borland C++ Compiler 5.5. Just execute the file freecommandLinetools.exe, and it will install the compiler. The default directory is C:\Borland 2. Install Apache HTTP Server. Execute httpd-2.2.21-win32-x86-no_ssl.msi file. And enter these config options when asked. By default it will be installed in C:\Program Files\Apache Software Foundation

3. Now you will see a feather like icon in your tray and if there is a green arrow in it, this means that Apache Server is running successfully

4. Also now open your browser, any browser, and type: http://localhost/ in it, you will see a text It works!, this means that the installation is successful. Now you are running a software in your PC which is capable of running web apps, which is a web server 5. Now, open the examples directory with this zip file, you will find some files in it 6. Now navigate to examples directory extracted from this zip file. You will find some files and a directory dummy in it

7. Now we have to compile the C codes in it. For that: 8. Navigate to C:\Borland\BCC55\Bin and create a file called bcc32.cfg and add these two lines in it and save it -I"C:\Borland\BCC55\Include" -L"C:\Borland\BCC55\Lib" Again, regarding path, if you have installed it in different location, use it. The pic below shows the snap of how my Compiler looks after this step

9. Now right-click My Computer and click Properties. And click “Advanced” tab, and click “Environment Variables”. Now search for “Path” variable. Edit it and add the location of bin directory of Borland Compiler as shown in the pic. Remember to use the semi-colon as shown in the diagram.

We do this step because, we have to allow the command prompt (DOS) to access the compiler from examples directory. 10. Now we have done everything required. Navigate to examples directory and now we are going to compile the C codes that we have there 11. Open DOS prompt, Click Start and click Run and then enter cmd in the textbox and press enter

12. This will open the dos prompt, now navigate to the location of example directory If you are new to DOS, don’t worry

Copy the entire location of the examples dir from windows explorer, as shown in 1st image, then in dos, write cd then inside double quotes paste(right click and paste) the location and then press enter 13. Now you are in examples dir inside DOS

14. I have shown an example of compiling index.c file, the command you have to enter is bcc32 index.c This will generate many files, don’t worry about it. If successful, you will see index.exe file in examples directory. Similarly, do it for all C files, home.c, login.c, logout.c 15. At the end of previous step, you must have index.exe, login.exe, logout.exe and home.exe files in examples dir along with some more files. Don’t worry about the other files 16. Now, copy ONLY the exe files (mentioned in step 15) and the five txt files(data1.txt, data2.txt, data3.txt, content.txt, form.txt) in examples dir to C:\Program Files\Apache Software Foundation\Apache2.2\cgi-bin Such that the directory looks like this:

Don’t worry about the file, if its by default. We don’t need it 17. Now ensure that your Apache Server is running (Step 3), and open browser and navigate to: http://localhost/cgi-bin/index.exe Remember, localhost doesn’t have a www or a .com, as its not a URL from Internet, its hosted local in your PC. The page should look like the image below. If you face any problems in this step try these steps: 1. Check if it works 2. Check if apache is running properly (Step 3 and Step 4)

18. Now the example project is set properly. Enjoy! The explanation of the project and the commands are given below in the same document. 19. Please don’t skip the example explanation section, as it contains one more important point about .c files in cgi-bin directory (PAGE 12, 13)

EXAMPLE PROJECT – EXPLANATION 1. The project contains files enough to explain the complete API and also simple web programming you require 2. Now open index.c from examples directory. The explanation is as follows: 1. 2. 3. 4. 5. 6. 7. 8. 9.

#include"web.h" main() { char msg[2]; initHtml(); includeFile("data1.txt"); printf("Welcome to my website"); includeFile("data2.txt"); printf("<center><h1>Welcome to my website</h1><marquee>Please login to continue...</marquee>"); 10. if(isset("GET","msg")==1) 11. { 12. returnGetString("msg",msg);

13. 14. 15. 16. 17. 18. 19.

} if(strcmp(msg,"1")==0) printf("<font color=\"red\">Invalid Username/Password combination</font>"); includeFile("form.txt"); printf("</center>"); includeFile("data3.txt"); }

Explanation: Line 1: We include web.h API that allows us to do web programming using C. If you are new to C, you might wonder why I have not include stdio.h, its actually included inside web.h, stdio.h, stdlib.h, string.h, time.h all headers are already include inside web.h, but if you include again also, no problem Line 5: initHtml() function is the place where after that what ever printf statements occur, they will throw their outputs to browser Line 6: includeFile() is a handy function to include contents from any external file. The advantage of this is that, you can change the external file anytime without re-compiling the C code. Here I have included few files, open the files in examples dir and see what they are. Basically they contain the static HTML content, that need to be given to the browser. If you donâ&#x20AC;&#x2122;t know HTML, donâ&#x20AC;&#x2122;t worry, at the end of this tutorial, I have given links for that For now, im leaving the other functions in this file, we will revisit this file after sometime 3. Now im going to talk about something interesting. Just imaging, a user logs in to your website, what you need to do? You need to check if his username and password are valid and if they are valid, you need to ensure that he is given access to some special pages which you wish to hide from guests without authorization. For that what we need? We need to store some information either in server or in users browser such that whenever user visits some special page, we need to check if that user is valid one based on the information stored. Such information, which is stored in clients browser



6. 7.

is called a Cookie. Since our API aims small apps, so Cookies are enough for our operations. Also, if you think, we need some kind of communication from page to page. Here in our case, the user enters his data in index.c file and it is sent to login.c for authentication, so we need a way to communicate from page to page. There are two ways for doing this purpose: one is by GET method and one is by POST method. The difference is pretty simple, again remember, we are talking about sending data from one page to another. One way is the data is sent in URL (address) itself (GET). Suppose from index.c I want to send some data by GET to login.c, the message to login.c will look like login.c?name=sriram&age=22 Any page can talk to login.c by this way, from login.c if you wish to know which page actually sent the request, that is through environment variables, that is discussed later Or else, you think that its unsafe to pass data via address itself, as it will be VISIBLE to others also, there is another way, we call the file and put data hidden (ď &#x160; HTTP Headers & Data, donâ&#x20AC;&#x2122;t worry about them!!). That way is called as POST Based on what you need, you can choose what you want, GET or POST In the example project I have shown both. Now coming back to index.exe file, when user clicks Login button, he is redirected to login.exe file, the C code of the file is as: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

#include"web.h" main() { char username[50],password[50]; returnPostString("user",username); returnPostString("pass",password); if(strcmp(username,"sriram")==0 && strcmp(password,"test123")==0) { setCookie("is_valid_session","1",3600*2); redirect("home.c"); } else { redirect("index.c?msg=1"); } initHtml();

17. }

Explanation: Line 4: I create two character arrays to hold username and password from previous index.exe page. Again open index.exe from browser and check its Source (RightClickViewSource)

You can see that I specify the location when user click submit to login.c (now you have only login.exe in cgi-bin, at the end you will have a new dummy file login.c also) and the method is POST, that’s why when I click submit, I cant see the data sent to login.c in URL as I said, its sent “hidden” Line 5,6: Now index.exe has sent something to login.c, which is sent by POST method, to receive that I use a method returnPostString(), which takes two arguments, the first agreement is the name of the field I sent from index.exe, again source of index.exe, you can see that I have named the text field of username as user and password as pass, so in login.exe I receive them with that name, and the next argument is the variable in login.exe where I need to store the received data. Thus after these lines, I have the message sent by index.exe. Then I check if username is “sriram” and password is “test123”

Now go to examples dir and go to dummy dir inside it, and copy all the files from it to /cgi-bin/

REMEMBER: Open any of the C file, you wonâ&#x20AC;&#x2122;t find any code in it, the ones with code are in examples folder, but this is just a dummy file. The reason why we need it is, if we keep on accessing exe files from browser, sometimes, some download software might think that these files are downloadable files and annoy

you by popping downloads, so its better to call them as .c files, internally the c files call the exe files using the shebang statement of CGI. Just open the file and give the absolute path from C: to each exe file in it. That’s all!! From now through browser we will access the exe files through the dummy c files only! Like index.c, login.c and NOT index.exe, login.exe Line 9: If the user is a valid user, we set a cookie in users PC, that is done by setCookie() function, it takes three arguments, the first is the name of the cookie and the second is the value of the cookie and the third argument is the time to which the cookie has to be alive in seconds.

The redirect() function is used to redirect to some other page. So, if the user is a valid user, we set cookie and then redirect to a protected page, home.c, else if the user enters a wrong details, we redirect to index.c but with a GET message ?msg=1, now again open index.c source code (examples dir), you will find that I first check if msg is set as a GET parameter by isset(“GET”,”msg”), its an integer function which returns 1 if its set or 0 otherways. And then I get the content by returnGetString() and then post, “Invalid details” accordingly

Similarly in home.c file, returnCookieString() is used to get cookie value. To see cookies set through browser, go to ToolsOptions. And go to “Privacy” and click “remove individual cookies”, now you can see what data our “localhost” has set in the users side. We set one cookie, check cookie name and content and time. We set everything in the code. Now we don’t need to send data from page to page, some data is stored centralized to all pages, and using the function returnCookieString() we can get the cookie value from any page after its set. And also using isset() function, its existence can be checked 

Last but not least, logout.c contains a function destroyCookie() which takes cookie name, after that check the cookie in browser again, it will be destroyed automatically. Thus, convert your simple C code into a web code!! !! REMEMBER, COOKIES ARE STORED IN USERS PC, SO THEY CAN BE MODIFICED BY USER, THEY ARE NOT SAFE UNLESS SOME CRYPTOGRAPHY IS USED !! FOR DATABASE FUNCTIONS, check MYSQL website and SQLite website, they provide APIs for C Database operation Also initHtml() method MUST be called in everypage, or else, browser wonâ&#x20AC;&#x2122;t show any result AND if you need to set or delete cookie, you MUST do it before calling initHtml()

Remember to use <br/> in printf(), not \n as HTML doesn’t understand \n for new line ADVANTAGES OF C AS A WEB LANGUAGE Unlike some languages like PHP, which are interpreted each and every time they are called, C is damn fast as its directly made as the machine instructions. For large apps, the speed performance will be awesome!

WHAT TO LEARN FOR WEB PROGRAMMING 1. Browsers have their own language which is much concern about how to display things like textbox, images, in browser, its called HTML 2. If you need to do some computing in browser side, Javascript 3. If you need to creative very interactive apps which can do processing without refreshing the page – AJAX 4. If you need to improve the styling of your HTML page – CSS 5. If you need database operations (Storing data, retrieving and so on) - SQL For all these languages, very simple, and good tutorial are found in Start learning atleast HTML for completing this course on web apps! Its mandatory!!! 6. Also, for web server, you can learn about Apache Web Server configurations. This will teach you a lot about security. Don’t forget to read about .htaccess files. 7. If you want some powerful database attached to your C code, download MYSQL or SQLite database api’s for C, search them in Internet and learn about them. For simple data storages, you can use file operations from C and store in small files itself. 8. Also if you need powerful server side languages as a substitute of C, then go for PHP, ASP, JSP/Servlets…

web.h API Reference (INTERNAL FUNCTIONS NOT SHOWN) 1. void initHtml(void) Usage: initHtml(); Description: Called before printing any data. But must be called ONLY after setting/deleting cookie or setting come HTTP header, deleteCache() and all. Otherwise the functions will not work. Check the example project 2. void setCookie(char* cookie_name,char* cookie_value,long cookie_life_seconds) Usage: setCookie(COOKIE_NAME,COOKIE_VALUE,TIME); Description: Sets a cookie of specified parameters and time limit to automatically expire 3. void destroyCookie(char* name) Usage: destroyCookie(COOKIE_NAME); Description: Removes a cookie which is already set 4. void returnGetString(char* name,char* result) Usage: returnGetString(GET_VARIABLE_NAME,TARGET); Description: Gets a string which is set by GET method and copies its value to target 5. void returnPostString(char* name,char* result) Usage: returnPostString(POST_VARIABLE_NAME,TARGET); Description: Gets a string which is set by POST method and copies its value to target 6. void returnCookieString(char* name,char* result) Usage: returnCookieString(GET_VARIABLE_NAME,TARGET); Description: Gets a string which is set as a cookie and copies its value to target 7. void includeFile(char* filename) Usage: includeFile(FILE_NAME); Description: Includes the contents of a file, which is static to the code at runtime 8. int isset(char* type,char* name) Usage:

int VAL=isset(“GET”,GET_VALUE_NAME); int VAL=isset(“POST”,POST_VALUE_NAME); int VAL=isset(“COOKIE”,COOKIE_VALUE_NAME); Description: Returns 1 if the particular combination is found, otherwise returns 0 9. In addition to all these functions the API provides, CGI provides variables through which you can know things like clients IP, Port, URL of page, browser of client and lot more: To use it Usage: getenv(“KEY_NAME”); Example: getenv(“REMOTE_ADDR”); gives IP of the client Other variables are:

You can find other variables, search in Internet, “CGI environment variables”, you will get more  (CHECK THE EXAMPLE PROJECT TO KNOW THE DEMO USAGE OF ALL THE ABOVE FUNCTIONS)

web.h API Reference (INTERNAL FUNCTIONS ONLY) 1. 2. 3. 4. 5.

char* returnRawGetString(void) char* returnRawPostString(void) char* returnRawCookieString(void) void unencode(char *src,char *dest) void commonParseLogic(char* string,char* name,char delimiter,char temp_delimiter,int allow_spaces,int only_isset,char* target) 6. void setHttpHeader(char* http_field,char* http_field_option)



Web Programming Using C / C++  

Create a web page and a whole website in simple C itself

Read more
Read more
Similar to
Popular now
Just for you