Tag: c++ with CGI

  • C++ with CGI

    Before doing example, You have to configure cgi-bin with apache server.
    If its done then try your first example.

    Open an empty file and write following c++ code.


    #include <iostream>
    using namespace std;

    int main ()
    {

    cout << "Content-type:text/html\n\n";
    cout << "Hello World - First CGI Program";

    return 0;
    }

    Now save this file with .cpp extension(example.cpp) in public_html/cgi-bin folder.
    Then compile that program.
    $ g++ -o example example.cpp

    This will create example file which is executable.
    Then open browser and open following link”

    localhost/~username/cgi-bin/example

    This will show you following o/p on browser.

    Hello World – First CGI Program

    If you find any problem then share it as comments.
    Thankyou.

  • CGI Configuration on Apache

    There are 3 ways to use CGI.

    • First Way
      When we install Apache server, then /usr/lib/cgi-bin folder is automatically created. You can place c++ files in that folder and execute them on browser(localhost/cgi-bin/example).
    • Second Way
      You can also configure /var/www/cgi-bin for CGI programming.
    • Third Way
      You can also configure cgi-bin in home directory as /public_html/cgi-bin.

    According to me 3rd way is best as its in home directory and we don’t have to use sudo while compiling or creating any file.

    Steps to configure cgi-bin in public_html and public_html. Run following commands in terminal

    1. $ sudo a2enmod cgi
    2. $ sudo a2enmod cgid
    3. $ sudo a2enmod userdir
    4. $ sudo service apache2 restart
    5. $ mkdir ~/public_html
    6. $ cd ~/public_html
    7. $ mkdir cgi-bin
    8. $ cd /etc/apache2
    9. $ sudo vim sites-available/default
    10. Add following text in file:
       ScriptAlias /cgi-bin/ /home/*/public_html/cgi-bin/
       <Directory "/home/*/public_html/cgi-bin">
               AllowOverride None
               Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
               SetHandler cgi-script
               Order allow,deny
               Allow from all
       </Directory>
      
    11. $ sudo service apache2 restart