Create a website using C++ as the server-side language
Let's get into, Server Side Language as C++
Setup Server Side Language: C++ program that communicates with an Apache server to run a Linux command and display the output on a web page
- to run the ‘ls’ command: to list all files and directories
1. Set Up Your Development Environment
- Install a C++ compiler. Linux, you likely already have a C++ compiler installed.
yum install cpp
2. Install Apache Server and start the Services
Here, I'm Using a Linux Platform (Amazon Linux)
#install the package
yum install httpd
#Start the services
systemctl start httpd
#enable it
systemctl enable httpd
- The server has started and running on port 80
3. Now Set up the server to add the web pages to server clients
Clients can now see the webpage on the URL
- Go to the default configured path to server pages
- CGI-bin: For Server side language
- HTML: Front-end Languages/websites
Follow the command to add server-side language as C++
#go to the path of Server Backend diretory
cd /var/www/cgi-bin
#create a file cli.cpp
vim cli.cpp
#add the cpp code
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
string command = "ls";
//popen to open the cmd string variable
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) {
cerr << "popen() failed!" << endl;
return 1;
}
// set the http response header
//pre tag of Html to show the same output
cout << "Content-Type: text/html\n\n";
cout << "<html><body><pre>";
char buffer[128];
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
cout << buffer;
}
pclose(pipe);
cout << "</pre></body></html>";
return 0;
}
- The popen() function opens a process by creating a pipe, forking, and invoking the shell.
Compile the C++ program
g++ cli.cpp -o cli.out
Ignore all other files as I performing the other demos.
Now we have the compiled file cli.out
4. Create a CGI Script
Open your Apache configuration file (usually located on Linux) and add the following lines to enable CGI scripts:
vim /etc/http/conf.d/welcome.conf
Append the following code: to make the scripts executable
Options +ExecCGI
AddHandler cgi-script .cgi .pl .sh .cpp
Add the path to your Cpp file to be executed on client request:
Create a file and add the path:
cd /var/www/cgi-bin
vim run_command.cgi
#!/bin/bash
/var/www/cgi-bin/cli.out
#/path/to/your/command_runner
- Now make the file executable
chmod +x run_command.cgi
#restart the Server
systemctl restart httpd
5. Run Your Server
In my case I have a public IP, you can add your IP or local host
Browser: http://43.204.130.223/cgi-bin/cli.out
- List the files on the current working directory of cgi-bin
That’s it! You’ve created a basic C++ program that communicates with an Apache server to run a Linux command and display the output on a web page.
Successfully Server-Side language of CPP has been Implemented..!!
Thank you