CGI programming with Octave

From GHER

Jump to: navigation, search


Contents

Installation

With the octave's package manager, you can install this software by issuing in an octave session the following command:

pkg install -forge -auto cgi

You can also get the lasted code version by:

svn checkout svn://svn.code.sf.net/p/octave/code/trunk/octave-forge/extra/cgi cgi

Add the inst folder to your path:

addpath('/path/to/cgi-x.y/inst');

Using CGI

The cgi package uses an object-oriented interface. First it is necessary to create a CGI objects which captures the current CGI environnement:

CGI = cgi();

The CGI query string can be accessed by getfrist (returns only the value of the first parameter with a given name) and getlist (returns all values of the parameters with a given name). For example, consider the URL http://example.com/cgi-bin/script.m?name=foo&name=bar

var = getfirst(CGI,'name'); % returns 'foo'
vars = getlist(CGI,'name'); % returns {'foo','bar'}

Instead of getfirst, you can also use the following syntax:

var = CGI.form.name;

More documentation is available at: http://octave.sourceforge.net/cgi/overview.html

Simple script

Create a file with the following content in your web-servers cgi-bin directory (the default in Debian/Ubuntu is /usr/lib/cgi-bin). Name the file for example hello.cgi.

#!/usr/local/bin/octave -qH
addpath('/home/abarth/Octave/cgi');
printf('Content-type: text/html\n\n');

CGI = cgi();
name = getfirst(CGI,'name','world'); % 'world' is the default parameter
printf('Hello %s',name);
printf('<form action="/cgi-bin/hello.cgi" method="get">');
printf('Your name<input type="text" name="name">');
printf('<input type="submit"></form>');
printf('</body></html>');

The first line should be path to your octave binary. You must use the -q option for quite. This file should be made executable:

sudo chmod +x hello.cgi

Open the URL with your web-browser http://example.com/cgi-bin/hello.cgi. Of course it is extremely tedious to generate HTML from octave. It is better to separate the HTML code and the octave code. The octave CGI script would for example return data in JSON and the HTML page is updated with JavaScript. The toolbox jsonlab can be used to generate JSON from octave.


Limitations

  • Only a CONTENT_TYPE "application/x-www-form-urlencoded" is supported for POST requests.
  • No file uploads
Personal tools