1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE manualpage SYSTEM "../style/manualpage.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
4 <!-- $LastChangedRevision$ -->
7 Licensed to the Apache Software Foundation (ASF) under one or more
8 contributor license agreements. See the NOTICE file distributed with
9 this work for additional information regarding copyright ownership.
10 The ASF licenses this file to You under the Apache License, Version 2.0
11 (the "License"); you may not use this file except in compliance with
12 the License. You may obtain a copy of the License at
14 http://www.apache.org/licenses/LICENSE-2.0
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
23 <manualpage metafile="cgi.xml.meta">
24 <parentdocument href="./">How-To / Tutorials</parentdocument>
26 <title>Apache Tutorial: Dynamic Content with CGI</title>
29 <title>Introduction</title>
33 <module>mod_alias</module>
34 <module>mod_cgi</module>
38 <directive module="mod_mime">AddHandler</directive>
39 <directive module="core">Options</directive>
40 <directive module="mod_alias">ScriptAlias</directive>
44 <p>The CGI (Common Gateway Interface) defines a way for a web
45 server to interact with external content-generating programs,
46 which are often referred to as CGI programs or CGI scripts. It
47 is the simplest, and most common, way to put dynamic content on
48 your web site. This document will be an introduction to setting
49 up CGI on your Apache web server, and getting started writing
53 <section id="configuring">
54 <title>Configuring Apache to permit CGI</title>
56 <p>In order to get your CGI programs to work properly, you'll
57 need to have Apache configured to permit CGI execution. There
58 are several ways to do this.</p>
60 <note type="warning">Note: If Apache has been built with shared module
61 support you need to ensure that the module is loaded; in your
62 <code>httpd.conf</code> you need to make sure the
63 <directive module="mod_so">LoadModule</directive>
64 directive has not been commented out. A correctly configured directive
68 LoadModule cgi_module modules/mod_cgi.so
71 <section id="scriptalias">
72 <title>ScriptAlias</title>
75 <directive module="mod_alias">ScriptAlias</directive>
77 directive tells Apache that a particular directory is set
78 aside for CGI programs. Apache will assume that every file in
79 this directory is a CGI program, and will attempt to execute
80 it, when that particular resource is requested by a
83 <p>The <directive module="mod_alias">ScriptAlias</directive>
84 directive looks like:</p>
87 ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/
90 <p>The example shown is from your default <code>httpd.conf</code>
91 configuration file, if you installed Apache in the default
92 location. The <directive module="mod_alias">ScriptAlias</directive>
93 directive is much like the <directive module="mod_alias"
94 >Alias</directive> directive, which defines a URL prefix that
95 is to mapped to a particular directory. <directive>Alias</directive>
96 and <directive>ScriptAlias</directive> are usually used for
97 directories that are outside of the <directive module="core"
98 >DocumentRoot</directive> directory. The difference between
99 <directive>Alias</directive> and <directive>ScriptAlias</directive>
100 is that <directive>ScriptAlias</directive> has the added meaning
101 that everything under that URL prefix will be considered a CGI
102 program. So, the example above tells Apache that any request for a
103 resource beginning with <code>/cgi-bin/</code> should be served from
104 the directory <code>/usr/local/apache2/cgi-bin/</code>, and should be
105 treated as a CGI program.</p>
107 <p>For example, if the URL
108 <code>http://www.example.com/cgi-bin/test.pl</code>
109 is requested, Apache will attempt to execute the file
110 <code>/usr/local/apache2/cgi-bin/test.pl</code>
111 and return the output. Of course, the file will have to
112 exist, and be executable, and return output in a particular
113 way, or Apache will return an error message.</p>
116 <section id="nonscriptalias">
117 <title>CGI outside of ScriptAlias directories</title>
119 <p>CGI programs are often restricted to <directive module="mod_alias"
120 >ScriptAlias</directive>'ed directories for security reasons.
121 In this way, administrators can tightly control who is allowed to
122 use CGI programs. However, if the proper security precautions are
123 taken, there is no reason why CGI programs cannot be run from
124 arbitrary directories. For example, you may wish to let users
125 have web content in their home directories with the
126 <directive module="mod_userdir">UserDir</directive> directive.
127 If they want to have their own CGI programs, but don't have access to
128 the main <code>cgi-bin</code> directory, they will need to be able to
129 run CGI programs elsewhere.</p>
131 <p>There are two steps to allowing CGI execution in an arbitrary
132 directory. First, the <code>cgi-script</code> handler must be
133 activated using the <directive
134 module="mod_mime">AddHandler</directive> or <directive
135 module="core">SetHandler</directive> directive. Second,
136 <code>ExecCGI</code> must be specified in the <directive
137 module="core">Options</directive> directive.</p>
140 <section id="options">
141 <title>Explicitly using Options to permit CGI execution</title>
143 <p>You could explicitly use the <directive module="core"
144 >Options</directive> directive, inside your main server configuration
145 file, to specify that CGI execution was permitted in a particular
149 <Directory /usr/local/apache2/htdocs/somedir><br />
151 Options +ExecCGI<br />
156 <p>The above directive tells Apache to permit the execution
157 of CGI files. You will also need to tell the server what
158 files are CGI files. The following <directive module="mod_mime"
159 >AddHandler</directive> directive tells the server to treat all
160 files with the <code>cgi</code> or <code>pl</code> extension as CGI
164 AddHandler cgi-script .cgi .pl
168 <section id="htaccess">
169 <title>.htaccess files</title>
171 <p>The <a href="htaccess.html"><code>.htaccess</code> tutorial</a>
172 shows how to activate CGI programs if you do not have
173 access to <code>httpd.conf</code>.</p>
176 <section id="userdir">
177 <title>User Directories</title>
179 <p>To allow CGI program execution for any file ending in
180 <code>.cgi</code> in users' directories, you can use the
181 following configuration.</p>
184 <Directory /home/*/public_html><br/>
186 Options +ExecCGI<br/>
187 AddHandler cgi-script .cgi<br/>
192 <p>If you wish designate a <code>cgi-bin</code> subdirectory of
193 a user's directory where everything will be treated as a CGI
194 program, you can use the following.</p>
197 <Directory /home/*/public_html/cgi-bin><br/>
200 SetHandler cgi-script<br/>
209 <section id="writing">
210 <title>Writing a CGI program</title>
212 <p>There are two main differences between ``regular''
213 programming, and CGI programming.</p>
215 <p>First, all output from your CGI program must be preceded by
216 a <glossary>MIME-type</glossary> header. This is HTTP header that tells the client
217 what sort of content it is receiving. Most of the time, this
221 Content-type: text/html
224 <p>Secondly, your output needs to be in HTML, or some other
225 format that a browser will be able to display. Most of the
226 time, this will be HTML, but occasionally you might write a CGI
227 program that outputs a gif image, or other non-HTML
230 <p>Apart from those two things, writing a CGI program will look
231 a lot like any other program that you might write.</p>
233 <section id="firstcgi">
234 <title>Your first CGI program</title>
236 <p>The following is an example CGI program that prints one
237 line to your browser. Type in the following, save it to a
238 file called <code>first.pl</code>, and put it in your
239 <code>cgi-bin</code> directory.</p>
242 #!/usr/bin/perl<br />
243 print "Content-type: text/html\n\n";<br />
244 print "Hello, World.";
247 <p>Even if you are not familiar with Perl, you should be able
248 to see what is happening here. The first line tells Apache
249 (or whatever shell you happen to be running under) that this
250 program can be executed by feeding the file to the
251 interpreter found at the location <code>/usr/bin/perl</code>.
252 The second line prints the content-type declaration we
253 talked about, followed by two carriage-return newline pairs.
254 This puts a blank line after the header, to indicate the end
255 of the HTTP headers, and the beginning of the body. The third
256 line prints the string "Hello, World.". And that's the end
259 <p>If you open your favorite browser and tell it to get the
263 http://www.example.com/cgi-bin/first.pl
266 <p>or wherever you put your file, you will see the one line
267 <code>Hello, World.</code> appear in your browser window.
268 It's not very exciting, but once you get that working, you'll
269 have a good chance of getting just about anything working.</p>
273 <section id="troubleshoot">
274 <title>But it's still not working!</title>
276 <p>There are four basic things that you may see in your browser
277 when you try to access your CGI program from the web:</p>
280 <dt>The output of your CGI program</dt>
281 <dd>Great! That means everything worked fine. If the output is correct,
282 but the browser is not processing it correctly, make sure you have the
283 correct <code>Content-Type</code> set in your CGI program.</dd>
285 <dt>The source code of your CGI program or a "POST Method Not
286 Allowed" message</dt>
287 <dd>That means that you have not properly configured Apache
288 to process your CGI program. Reread the section on
289 <a href="#configuring">configuring
290 Apache</a> and try to find what you missed.</dd>
292 <dt>A message starting with "Forbidden"</dt>
293 <dd>That means that there is a permissions problem. Check the
294 <a href="#errorlogs">Apache error log</a> and the section below on
295 <a href="#permissions">file permissions</a>.</dd>
297 <dt>A message saying "Internal Server Error"</dt>
299 <a href="#errorlogs">Apache error log</a>, you will probably
300 find that it says "Premature end of
301 script headers", possibly along with an error message
302 generated by your CGI program. In this case, you will want to
303 check each of the below sections to see what might be
304 preventing your CGI program from emitting the proper HTTP
308 <section id="permissions">
309 <title>File permissions</title>
311 <p>Remember that the server does not run as you. That is,
312 when the server starts up, it is running with the permissions
313 of an unprivileged user - usually <code>nobody</code>, or
314 <code>www</code> - and so it will need extra permissions to
315 execute files that are owned by you. Usually, the way to give
316 a file sufficient permissions to be executed by <code>nobody</code>
317 is to give everyone execute permission on the file:</p>
323 <p>Also, if your program reads from, or writes to, any other
324 files, those files will need to have the correct permissions
329 <section id="pathinformation">
330 <title>Path information and environment</title>
332 <p>When you run a program from your command line, you have
333 certain information that is passed to the shell without you
334 thinking about it. For example, you have a <code>PATH</code>,
335 which tells the shell where it can look for files that you
338 <p>When a program runs through the web server as a CGI program,
339 it may not have the same <code>PATH</code>. Any programs that you
340 invoke in your CGI program (like <code>sendmail</code>, for
341 example) will need to be specified by a full path, so that the
342 shell can find them when it attempts to execute your CGI
345 <p>A common manifestation of this is the path to the script
346 interpreter (often <code>perl</code>) indicated in the first
347 line of your CGI program, which will look something like:</p>
353 <p>Make sure that this is in fact the path to the
356 <p>In addition, if your CGI program depends on other <a
357 href="#env">environment variables</a>, you will need to
358 assure that those variables are passed by Apache.</p>
362 <section id="syntaxerrors">
363 <title>Program errors</title>
365 <p>Most of the time when a CGI program fails, it's because of
366 a problem with the program itself. This is particularly true
367 once you get the hang of this CGI stuff, and no longer make
368 the above two mistakes. The first thing to do is to make
369 sure that your program runs from the command line before
370 testing it via the web server. For example, try:</p>
373 cd /usr/local/apache2/cgi-bin<br/>
377 <p>(Do not call the <code>perl</code> interpreter. The shell
378 and Apache should find the interpreter using the <a
379 href="#pathinformation">path information</a> on the first line of
382 <p>The first thing you see written by your program should be
383 a set of HTTP headers, including the <code>Content-Type</code>,
384 followed by a blank line. If you see anything else, Apache will
385 return the <code>Premature end of script headers</code> error if
386 you try to run it through the server. See <a
387 href="#writing">Writing a CGI program</a> above for more
391 <section id="errorlogs">
392 <title>Error logs</title>
394 <p>The error logs are your friend. Anything that goes wrong
395 generates message in the error log. You should always look
396 there first. If the place where you are hosting your web site
397 does not permit you access to the error log, you should
398 probably host your site somewhere else. Learn to read the
399 error logs, and you'll find that almost all of your problems
400 are quickly identified, and quickly solved.</p>
403 <section id="suexec">
404 <title>Suexec</title>
406 <p>The <a href="../suexec.html">suexec</a> support program
407 allows CGI programs to be run under different user permissions,
408 depending on which virtual host or user home directory they are
409 located in. Suexec has very strict permission checking, and any
410 failure in that checking will result in your CGI programs
411 failing with <code>Premature end of script headers</code>.</p>
413 <p>To check if you are using suexec, run <code>apachectl
414 -V</code> and check for the location of <code>SUEXEC_BIN</code>.
415 If Apache finds an <program>suexec</program> binary there on startup,
416 suexec will be activated.</p>
418 <p>Unless you fully understand suexec, you should not be using it.
419 To disable suexec, simply remove (or rename) the <program>suexec</program>
420 binary pointed to by <code>SUEXEC_BIN</code> and then restart the
421 server. If, after reading about <a href="../suexec.html">suexec</a>,
422 you still wish to use it, then run <code>suexec -V</code> to find
423 the location of the suexec log file, and use that log file to
424 find what policy you are violating.</p>
428 <section id="behindscenes">
429 <title>What's going on behind the scenes?</title>
431 <p>As you become more advanced in CGI programming, it will
432 become useful to understand more about what's happening behind
433 the scenes. Specifically, how the browser and server
434 communicate with one another. Because although it's all very
435 well to write a program that prints "Hello, World.", it's not
436 particularly useful.</p>
439 <title>Environment variables</title>
441 <p>Environment variables are values that float around you as
442 you use your computer. They are useful things like your path
443 (where the computer searches for the actual file
444 implementing a command when you type it), your username, your
445 terminal type, and so on. For a full list of your normal,
446 every day environment variables, type
447 <code>env</code> at a command prompt.</p>
449 <p>During the CGI transaction, the server and the browser
450 also set environment variables, so that they can communicate
451 with one another. These are things like the browser type
452 (Netscape, IE, Lynx), the server type (Apache, IIS, WebSite),
453 the name of the CGI program that is being run, and so on.</p>
455 <p>These variables are available to the CGI programmer, and
456 are half of the story of the client-server communication. The
457 complete list of required variables is at
458 <a href="http://hoohoo.ncsa.uiuc.edu/cgi/env.html"
459 >http://hoohoo.ncsa.uiuc.edu/cgi/env.html</a>.</p>
461 <p>This simple Perl CGI program will display all of the
462 environment variables that are being passed around. Two
463 similar programs are included in the
466 directory of the Apache distribution. Note that some
467 variables are required, while others are optional, so you may
468 see some variables listed that were not in the official list.
469 In addition, Apache provides many different ways for you to
470 <a href="../env.html">add your own environment variables</a>
471 to the basic ones provided by default.</p>
474 #!/usr/bin/perl<br />
475 print "Content-type: text/html\n\n";<br />
476 foreach $key (keys %ENV) {<br />
478 print "$key --> $ENV{$key}<br>";<br />
485 <title>STDIN and STDOUT</title>
487 <p>Other communication between the server and the client
488 happens over standard input (<code>STDIN</code>) and standard
489 output (<code>STDOUT</code>). In normal everyday context,
490 <code>STDIN</code> means the keyboard, or a file that a
491 program is given to act on, and <code>STDOUT</code>
492 usually means the console or screen.</p>
494 <p>When you <code>POST</code> a web form to a CGI program,
495 the data in that form is bundled up into a special format
496 and gets delivered to your CGI program over <code>STDIN</code>.
497 The program then can process that data as though it was
498 coming in from the keyboard, or from a file</p>
500 <p>The "special format" is very simple. A field name and
501 its value are joined together with an equals (=) sign, and
502 pairs of values are joined together with an ampersand
503 (&). Inconvenient characters like spaces, ampersands, and
504 equals signs, are converted into their hex equivalent so that
505 they don't gum up the works. The whole data string might look
509 name=Rich%20Bowen&city=Lexington&state=KY&sidekick=Squirrel%20Monkey
512 <p>You'll sometimes also see this type of string appended to
513 a URL. When that is done, the server puts that string
514 into the environment variable called
515 <code>QUERY_STRING</code>. That's called a <code>GET</code>
516 request. Your HTML form specifies whether a <code>GET</code>
517 or a <code>POST</code> is used to deliver the data, by setting the
518 <code>METHOD</code> attribute in the <code>FORM</code> tag.</p>
520 <p>Your program is then responsible for splitting that string
521 up into useful information. Fortunately, there are libraries
522 and modules available to help you process this data, as well
523 as handle other of the aspects of your CGI program.</p>
527 <section id="libraries">
528 <title>CGI modules/libraries</title>
530 <p>When you write CGI programs, you should consider using a
531 code library, or module, to do most of the grunt work for you.
532 This leads to fewer errors, and faster development.</p>
534 <p>If you're writing CGI programs in Perl, modules are
535 available on <a href="http://www.cpan.org/">CPAN</a>. The most
536 popular module for this purpose is <code>CGI.pm</code>. You might
537 also consider <code>CGI::Lite</code>, which implements a minimal
538 set of functionality, which is all you need in most programs.</p>
540 <p>If you're writing CGI programs in C, there are a variety of
541 options. One of these is the <code>CGIC</code> library, from
542 <a href="http://www.boutell.com/cgic/"
543 >http://www.boutell.com/cgic/</a>.</p>
546 <section id="moreinfo">
547 <title>For more information</title>
549 <p>There are a large number of CGI resources on the web. You
550 can discuss CGI problems with other users on the Usenet group
551 <a href="news:comp.infosystems.www.authoring.cgi"
552 >comp.infosystems.www.authoring.cgi</a>. And the -servers mailing
553 list from the HTML Writers Guild is a great source of answers
554 to your questions. You can find out more at
555 <a href="http://www.hwg.org/lists/hwg-servers/"
556 >http://www.hwg.org/lists/hwg-servers/</a>.</p>
558 <p>And, of course, you should probably read the CGI
559 specification, which has all the details on the operation of
560 CGI programs. You can find the original version at the
561 <a href="http://hoohoo.ncsa.uiuc.edu/cgi/interface.html"
562 >NCSA</a> and the current IETF RFC
563 <a href="http://www.ietf.org/rfc/rfc3875">Common Gateway
564 Interface RFC</a>.</p>
566 <p>When you post a question about a CGI problem that you're
567 having, whether to a mailing list, or to a newsgroup, make sure
568 you provide enough information about what happened, what you
569 expected to happen, and how what actually happened was
570 different, what server you're running, what language your CGI
571 program was in, and, if possible, the offending code. This will
572 make finding your problem much simpler.</p>
574 <p>Note that questions about CGI problems should <strong>never</strong>
575 be posted to the Apache bug database unless you are sure you
576 have found a problem in the Apache source code.</p>