How To Use C++ CGI Script? - c++

I am currently enrolled in a web applications class at my college and we are learning about cgi scripts. I am having a hard time learning how to implement my CGI script. When I click on my link a window pops up asking me to download my helloworld.cgi file instead of just redirecting.
HTML:
<html>
<body>
click me
</body>
</html>
C++:
#include <iostream>
using namespace std;
int main(){
cout << "Content-type: text/html" << endl;
cout << "<html>" << endl;
cout << " <body>" << endl;
cout << " Hello World!" << endl;
cout << " </body>" << endl;
cout << "</html>" << endl;
return 0;
}
The CGI script is stored at /user/local/apache2/cgi-bin/helloworld.cgi

You need to compile the C++ file, and call the result helloworld.cgi. C++ is not a scripting language -- you can't just deploy it to your server.
On a typical *nix system, name the C++ file helloworld.cpp
gcc -o helloworld.cgi helloworld.cpp
Then put that file in your cgi-bin
Edit: you need two endl's after the last header item
cout << "Content-type: text/html" << endl << endl;

/user/local/apache2/cgi-bin/helloworld.cgi is the physical path of the file on your hard disk. To run the script through Apache, you need to specify the path relative to your server's document root, for eg. http://localhost/cgi-bin/helloworld.cgi.

I had this problem too, and this solution worked for me :
First run this commands on terminal:
sudo a2enmod cgi
sudo service apache2 restart
Then copy helloworld.cgi to /usr/lib/cgi-bin/
sudo cp helloworld.cgi /usr/lib/cgi-bin/
And finally change href link to:
click me

You just need to configure Apache to recognise a cgi-bin properly...
Have a read of this: http://httpd.apache.org/docs/1.3/howto/cgi.html
In Apache config ScriptAlias is probably what you want.
(I'm assuming you've compiled the binary to helloworld.cgi)

Related

How to run SSH with system() in C++

I've written a simple program to connect to a Linux server using SSH via my C++ program. Here's the code:
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int main()
{
string hostIP;
string username;
string password;
cout << "Welcome to SSH Program" << endl;
cout << "----------------------" << endl;
cout << "\nEnter host ip or name Example: \"capa.its.uow.edu.au\": ";
cin >> hostIP;
cout << "Enter username: ";
cin >> username;
cout << "\nConnecting...\n" << endl;
string composite = "ssh " + username + "#" + hostIP;
char command[100];
strcpy(command, composite.c_str());
system(command);
system("pause");
}
It runs well on Ubuntu, but when I compile this same code on Visual Studio in Windows and execute it, the console present me with this error: 'ssh.exe' is not recognized as an internal or external command, operable program or batch file.
This didn't make sense to me because OpenSSH Client is clearly installed on my computer and I'm able to establish an SSH connection if I directly enter ssh username#server.ip.address in the command prompt.
I thought it might be an issue with the environment paths and so in Visual Studio, I checked Project>Properties>VC++ Directories>Executable Directories. There I found C:\WINDOWS\System32\OpenSSH\ among other paths, located in the Evaluated value: box.
Doesn't this mean everything should run fine since the OpenSSH directory is located in the path? Also, like I said, I am able to connect via SSH if I enter the command directly into the command prompt instead of the program.
Please help. I've been really scratching my head over this since last night.
I've managed to solve this issue. It seems to have been a problem with the selected platform in Visual Studio. Initially the platform for the project was set for an x86 architecture. This is the reason why ssh.exe could not be accessed even though it was present in the environment path.
By changing the platform to 64-bit architecture in the project properties, the program could reference the correct environment variables and execute ssh.exe as intended.

c++ for unix command line operation

I have a remote unix shell which I log on often to checkout files with but the system keep resetting my locals setting when I logon to it.
I was planning to write the code to execute a list of commands when I log on.
#include<iostream>
#include<stdlib.h>
int main(){
char javah[]="JAVA_HOME=/appl/usr/jdk/jdk1.6.0_20";
char anth[]="ANT_HOME=/appl/usr/ant/instances/1.8.2";
char path[]="PATH=$ANT_HOME/bin:$PATH";
system("bash");
system("cd");
system("cd insurancePPC.11");
system("0x0C");
system("ls");
putenv(javah);
putenv(anth);
putenv(path);
std::cout << "JAVA_HOME=" << getenv("JAVA_HOME");
std::cout << "\n";
std::cout << "ANT_HOME=" << getenv("ANT_HOME");
std::cout << "\n";
std::cout << "PATH=" << getenv("PATH");
std::cout << "\n";
system("cd tools");
std::cout << "command executed successfully...\n";
return 0;
}
Can anyone tell me why this wasn't working as expected?
cd is a built in command of the shell and only affects the current process (i.e. the current running shell.)
When you run system("cd insurancePPC.11"); it starts a new shell, that new shell changes the directory to insurancePPC.11 and exits. Your own process is unaffected by that cd command.
You are much better off writing these commands in a text file and run it as a shell script via the source command.
Create a file named myenv.sh with this content:
JAVA_HOME=/appl/usr/jdk/jdk1.6.0_20
export JAVA_HOME
ANT_HOME=/appl/usr/ant/instances/1.8.2
export ANT_HOME
PATH=$ANT_HOME/bin:$PATH
export PATH
cd
cd insurancePPC.11
ls
echo JAVA_HOME=$JAVA_HOME
echo ANT_HOME=$ANT_HOME
echo PATH=$PATH
cd tools
And from your command line run source myenv.sh Or if your shell supports it, use the shorthand . myenv.sh
There's no need to write a C program here. Just save the following as mysettings.sh:
export JAVA_HOME=/appl/usr/jdk/jdk1.6.0_20
export ANT_HOME=/appl/usr/ant/instances/1.8.2
PATH=$ANT_HOME/bin:$PATH
cd tools
When you log in, run
. mysettings.sh

Eclipse- C/C++ <terminated, exit value: -1073741515>

I recently decided to learn C/C++ in preparation for a coding class I will take in a few months so I downloaded and installed Eclipse. When I was going through the tutorials for the HelloWorld project, I ran into a problem where even though the code compiled perfectly fine, the console would not output "HelloWorld!" When I ran the debugger, it said that it was terminated and that the exit value was -1073741515 followed by my directory "C:\Users\Example\workspace\HelloWorld\Debug\HelloWorld.exe" followed by the date and time.
I installed MinGW and I set my path for eclipse to C:\MinGW\bin which is where it is in my directory and I checked to make sure my preferences were right because prior to this I was having some "program g++ not found in PATH" and "program gcc not found in PATH" These errors were fixed when I changed the environment variables.
When I continued to follow the tutorial, along with the HelloWorld.cpp which contained this code
#include <iostream>
using namespace std;
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
Next, they told me to write a main.cpp which contained this code
#include <iostream>
using namespace std;
int main() {
// Say Helloworld five times
for (int index = 0; index < 5; ++index)
cout << "HellowWorld!" << endl;
char input = 'i';
cout << "To exit, press 'm' then the 'Enter' key." << endl;
cin >> input;
while(input != 'm') {
cout << "You just entered '" << input << "'. "
<< "You need to enter 'm' to exit." << endl;
cin >> input;
}
cout << "Thank you. Exiting." << endl;
return 0;
}
Finally, they told me to create a makefile to help build and run my project which contained this code:
all: hello.exe
clean:
rm main.o hello.exe
hello.exe: main.o
g++ -g -o hello main.o
main.o:
g++ -c -g main.cpp
What this program should be doing is just printing out "HelloWorld!" five times in the console, but it is not and is just returning the "terminated, exit value: -1073741515" I'm really confused as to why this is. Can someone please help me? Thank you all.
I have some experience with Eclipse C/C++
The first thing that I suggest is that you do a test by starting a new project and then click on the 'new hello world' option rather than 'empty project' that should set up all of your project. - When you have done this you should be able to run the program using the buttons in Eclipse.
If it works you are done - you can modify the program to whatever you wish and everything is made for ou.
If it does not work you have an issues, most likely with Eclipse not finding the compiler. You may be able to tell this when you start a new project as it will show the compilers that it has found on the right hand side of a start project window.
Hope this helps. In my experience Eclipse is really great, but has so many options it can be a little daunting and I know I don't use all the potential it has.
If you are really stuck try using PELLES instead of Eclipse - in my experience this is alot easier to get started with.
Your path settings may not be carrying through to your toolchain. To be sure, add the full path to your MinGW binaries folder to your Windows path and restart. (Cygwin binaries folder (C:\Cygwin64\bin, on my system) for Cygwin users).

How to connect mySQL database using C++

I'm trying to connect the database from my website and display some rows using C++.
So bascily I'm trying to make an application that does a select query from a table from my site database. Now, this must be possible because I've seen tons of applications doing it.
How do I do this? Can some one make an example and tell me what libraries I should be using?
Found here:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
Finally I could successfully compile a program with C++ connector in Ubuntu 12.04
I have installed the connector using this command
'apt-get install libmysqlcppconn-dev'
Initially I faced the same problem with "undefined reference to `get_driver_instance' " to solve this I declare my driver instance variable of MySQL_Driver type. For ready reference this type is defined in mysql_driver.h file. Here is the code snippet I used in my program.
sql::mysql::MySQL_Driver *driver;
try {
driver = sql::mysql::get_driver_instance();
}
and I compiled the program with -l mysqlcppconn linker option
and don't forget to include this header
#include "mysql_driver.h"
Yes, you will need the mysql c++ connector library. Read on below, where I explain how to get the example given by mysql developers to work.
Note(and solution): IDE: I tried using Visual Studio 2010, but just a few sconds ago got this all to work, it seems like I missed it in the manual, but it suggests to use Visual Studio 2008. I downloaded and installed VS2008 Express for c++, followed the steps in chapter 5 of manual and errors are gone! It works. I'm happy, problem solved. Except for the one on how to get it to work on newer versions of visual studio. You should try the mysql for visual studio addon which maybe will get vs2010 or higher to connect successfully. It can be downloaded from mysql website
Whilst trying to get the example mentioned above to work, I find myself here from difficulties due to changes to the mysql dev website. I apologise for writing this as an answer, since I can't comment yet, and will edit this as I discover what to do and find the solution, so that future developers can be helped.(Since this has gotten so big it wouldn't have fitted as a comment anyways, haha)
#hd1 link to "an example" no longer works. Following the link, one will end up at the page which gives you link to the main manual. The main manual is a good reference, but seems to be quite old and outdated, and difficult for new developers, since we have no experience especially if we missing a certain file, and then what to add.
#hd1's link has moved, and can be found with a quick search by removing the url components, keeping just the article name, here it is anyways: http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-complete-example-1.html
Getting 7.5 MySQL Connector/C++ Complete Example 1 to work
Downloads:
-Get the mysql c++ connector, even though it is bigger choose the installer package, not the zip.
-Get the boost libraries from boost.org, since boost is used in connection.h and mysql_connection.h from the mysql c++ connector
Now proceed:
-Install the connector to your c drive, then go to your mysql server install folder/lib and copy all libmysql files, and paste in your connector install folder/lib/opt
-Extract the boost library to your c drive
Next:
It is alright to copy the code as it is from the example(linked above, and ofcourse into a new c++ project). You will notice errors:
-First: change
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
to
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
Not sure what that tiny double arrow is for, but I don't think it is part of c++
-Second: Fix other errors of them by reading Chapter 5 of the sql manual, note my paragraph regarding chapter 5 below
[Note 1]: Chapter 5 Building MySQL Connector/C++ Windows Applications with Microsoft Visual Studio
If you follow this chapter, using latest c++ connecter, you will likely see that what is in your connector folder and what is shown in the images are quite different. Whether you look in the mysql server installation include and lib folders or in the mysql c++ connector folders' include and lib folders, it will not match perfectly unless they update the manual, or you had a magic download, but for me they don't match with a connector download initiated March 2014.
Just follow that chapter 5,
-But for c/c++, General, Additional Include Directories include the "include" folder from the connector you installed, not server install folder
-While doing the above, also include your boost folder see note 2 below
-And for the Linker, General.. etc use the opt folder from connector/lib/opt
*[Note 2]*A second include needs to happen, you need to include from the boost library variant.hpp,
this is done the same as above, add the main folder you extracted from the boost zip download, not boost or lib or the subfolder "variant" found in boostmainfolder/boost.. Just the main folder as the second include
Next:
What is next I think is the Static Build, well it is what I did anyways. Follow it.
Then build/compile. LNK errors show up(Edit: Gone after changing ide to visual studio 2008). I think it is because I should build connector myself(if you do this in visual studio 2010 then link errors should disappear), but been working on trying to get this to work since Thursday, will see if I have the motivation to see this through after a good night sleep(and did and now finished :) ).
I had to include -lmysqlcppconn to my build in order to get it to work.

how to change the working directory to the location of the program

I want to use c++ to open a file on Mac OS.
If I run the program under Xcode, the working directory is the same with the program, which is fine. However, if I try to run the program in terminal, the working directory is alway "Users/username". Do you know how to change the working directory to the location of the program?
Here is the sample code:
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, const char * argv[])
{
char * dir = getcwd(NULL, 0);
cout << "Current dir: " << dir << endl;
ifstream fin("hi.txt");
if (fin.is_open()) cout << "File is Open" << endl;
else cout << "File is not open" << endl;
fin.close();
return 0;
}
Use the value $(PROJECT_DIR) in the working directory in your scheme debug settings:
You can set a custom working directory for your project in Xcode. In Xcode 4 choose Edit Scheme from the Scheme menu in the project window toolbar to open the scheme editor. Select the Run step from the left side of the project editor. Click the Options button at the top of the scheme editor. Select the Use custom working directory checkbox. Click the button on the right side of the text field to choose the working directory.
This is a really old post - updating some info for Xcode 12 (Sept 2020)
Step 1). Xcode -> Product -> Scheme -> Edit Scheme (or create a new one)
Step 2) RUN(DEBUG), Working Directory(Checkmark) and enter $(PROJECT_DIR) as a starting point.
You could use chdir(), see here: Change the current working directory in C++.
Or if you could always just issue a system call (stdlib.h): http://www.cplusplus.com/reference/clibrary/cstdlib/system/. This won't be portable, but it might be good enough for what you need.