Create a simple CGI server for Python

Sometimes there is a need that python scripts are executed directly from the browser. With CGIHTTPServer it goes very easily.

Create Folders

# create project folder
$ mkdir MyProject

# create cgi-bin folder
$ mkdir MyProject/cgi-bin

Create Python File

# create
$ touch MyProject/cgi-bin/

# modify
$ vim MyProject/cgi-bin/

Add some very simple content like:

#!/usr/bin/env python

print "Content-Type: text/html\n"
print "<html><head><title>Hello world</title></head>"
print "<body>"
print "<h1>hello world...</h1>"
print "<body>\n</html>"

Change the file permission

# change the permission
$ chmod 750 MyProject/cgi-bin/


# change to project folder
$ cd MyProject/

# run CGIHTTPServer
$ python -m CGIHTTPServer

Now open the browser and call URL: “http://localhost:8000/cgi-bin/

Python 3

In Python 3.3, the replacement for python -m CGIHTTPServer is python3 -m http.server --cgi.

Other examples

# show help
$ python3 -m http.server --help

# run server in Python 3
$ python3 -m http.server 8080

# run server in Python 3 on loopback interface
$ python3 -m http.server 8080 --bind

Fast PHP server

Since PHP 4.x, there is a CLI SAPI web server. As a tester you simply go to the folder and start the server.


# change to directory where server should start
$ cd /path/to/folder

# start server with specific port
$ php -S localhost:8100

Now start your browser and insert the URL “localhost:8100”. With “Ctrl+c” you can stop the server.


# explicit document root
$ cd /path/to/folder
$ php -S localhost:8100 -t foo/bar/

# specific configuration
$ cd /path/to/folder
$ php -S localhost:8100 -c php.ini