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
355 <note type="warning">
356 When editing CGI scripts on Windows, end-of-line characters may be
357 appended to the interpreter path. Ensure that files are then
358 transferred to the server in ASCII mode. Failure to do so may
359 result in "Command not found" warnings from the OS, due to the
360 unrecognized end-of-line character being interpreted as a part of
361 the interpreter filename.
365 <section id="missingenv">
366 <title>Missing environment variables</title>
368 <p>If your CGI program depends on non-standard <a
369 href="#env">environment variables</a>, you will need to
370 assure that those variables are passed by Apache.</p>
372 <p>When you miss HTTP headers from the environment, make
373 sure they are formatted according to
374 <a href="http://tools.ietf.org/html/rfc2616">RFC 2616</a>,
375 section 4.2: Header names must start with a letter,
376 followed only by letters, numbers or hyphen. Any header
377 violating this rule will be dropped silently.</p>
381 <section id="syntaxerrors">
382 <title>Program errors</title>
384 <p>Most of the time when a CGI program fails, it's because of
385 a problem with the program itself. This is particularly true
386 once you get the hang of this CGI stuff, and no longer make
387 the above two mistakes. The first thing to do is to make
388 sure that your program runs from the command line before
389 testing it via the web server. For example, try:</p>
392 cd /usr/local/apache2/cgi-bin<br/>
396 <p>(Do not call the <code>perl</code> interpreter. The shell
397 and Apache should find the interpreter using the <a
398 href="#pathinformation">path information</a> on the first line of
401 <p>The first thing you see written by your program should be
402 a set of HTTP headers, including the <code>Content-Type</code>,
403 followed by a blank line. If you see anything else, Apache will
404 return the <code>Premature end of script headers</code> error if
405 you try to run it through the server. See <a
406 href="#writing">Writing a CGI program</a> above for more
410 <section id="errorlogs">
411 <title>Error logs</title>
413 <p>The error logs are your friend. Anything that goes wrong
414 generates message in the error log. You should always look
415 there first. If the place where you are hosting your web site
416 does not permit you access to the error log, you should
417 probably host your site somewhere else. Learn to read the
418 error logs, and you'll find that almost all of your problems
419 are quickly identified, and quickly solved.</p>
422 <section id="suexec">
423 <title>Suexec</title>
425 <p>The <a href="../suexec.html">suexec</a> support program
426 allows CGI programs to be run under different user permissions,
427 depending on which virtual host or user home directory they are
428 located in. Suexec has very strict permission checking, and any
429 failure in that checking will result in your CGI programs
430 failing with <code>Premature end of script headers</code>.</p>
432 <p>To check if you are using suexec, run <code>apachectl
433 -V</code> and check for the location of <code>SUEXEC_BIN</code>.
434 If Apache finds an <program>suexec</program> binary there on startup,
435 suexec will be activated.</p>
437 <p>Unless you fully understand suexec, you should not be using it.
438 To disable suexec, simply remove (or rename) the <program>suexec</program>
439 binary pointed to by <code>SUEXEC_BIN</code> and then restart the
440 server. If, after reading about <a href="../suexec.html">suexec</a>,
441 you still wish to use it, then run <code>suexec -V</code> to find
442 the location of the suexec log file, and use that log file to
443 find what policy you are violating.</p>
447 <section id="behindscenes">
448 <title>What's going on behind the scenes?</title>
450 <p>As you become more advanced in CGI programming, it will
451 become useful to understand more about what's happening behind
452 the scenes. Specifically, how the browser and server
453 communicate with one another. Because although it's all very
454 well to write a program that prints "Hello, World.", it's not
455 particularly useful.</p>
458 <title>Environment variables</title>
460 <p>Environment variables are values that float around you as
461 you use your computer. They are useful things like your path
462 (where the computer searches for the actual file
463 implementing a command when you type it), your username, your
464 terminal type, and so on. For a full list of your normal,
465 every day environment variables, type
466 <code>env</code> at a command prompt.</p>
468 <p>During the CGI transaction, the server and the browser
469 also set environment variables, so that they can communicate
470 with one another. These are things like the browser type
471 (Netscape, IE, Lynx), the server type (Apache, IIS, WebSite),
472 the name of the CGI program that is being run, and so on.</p>
474 <p>These variables are available to the CGI programmer, and
475 are half of the story of the client-server communication. The
476 complete list of required variables is at
477 <a href="http://www.ietf.org/rfc/rfc3875">Common Gateway
478 Interface RFC</a>.</p>
480 <p>This simple Perl CGI program will display all of the
481 environment variables that are being passed around. Two
482 similar programs are included in the
485 directory of the Apache distribution. Note that some
486 variables are required, while others are optional, so you may
487 see some variables listed that were not in the official list.
488 In addition, Apache provides many different ways for you to
489 <a href="../env.html">add your own environment variables</a>
490 to the basic ones provided by default.</p>
493 #!/usr/bin/perl<br />
494 print "Content-type: text/html\n\n";<br />
495 foreach $key (keys %ENV) {<br />
497 print "$key --> $ENV{$key}<br>";<br />
504 <title>STDIN and STDOUT</title>
506 <p>Other communication between the server and the client
507 happens over standard input (<code>STDIN</code>) and standard
508 output (<code>STDOUT</code>). In normal everyday context,
509 <code>STDIN</code> means the keyboard, or a file that a
510 program is given to act on, and <code>STDOUT</code>
511 usually means the console or screen.</p>
513 <p>When you <code>POST</code> a web form to a CGI program,
514 the data in that form is bundled up into a special format
515 and gets delivered to your CGI program over <code>STDIN</code>.
516 The program then can process that data as though it was
517 coming in from the keyboard, or from a file</p>
519 <p>The "special format" is very simple. A field name and
520 its value are joined together with an equals (=) sign, and
521 pairs of values are joined together with an ampersand
522 (&). Inconvenient characters like spaces, ampersands, and
523 equals signs, are converted into their hex equivalent so that
524 they don't gum up the works. The whole data string might look
528 name=Rich%20Bowen&city=Lexington&state=KY&sidekick=Squirrel%20Monkey
531 <p>You'll sometimes also see this type of string appended to
532 a URL. When that is done, the server puts that string
533 into the environment variable called
534 <code>QUERY_STRING</code>. That's called a <code>GET</code>
535 request. Your HTML form specifies whether a <code>GET</code>
536 or a <code>POST</code> is used to deliver the data, by setting the
537 <code>METHOD</code> attribute in the <code>FORM</code> tag.</p>
539 <p>Your program is then responsible for splitting that string
540 up into useful information. Fortunately, there are libraries
541 and modules available to help you process this data, as well
542 as handle other of the aspects of your CGI program.</p>
546 <section id="libraries">
547 <title>CGI modules/libraries</title>
549 <p>When you write CGI programs, you should consider using a
550 code library, or module, to do most of the grunt work for you.
551 This leads to fewer errors, and faster development.</p>
553 <p>If you're writing CGI programs in Perl, modules are
554 available on <a href="http://www.cpan.org/">CPAN</a>. The most
555 popular module for this purpose is <code>CGI.pm</code>. You might
556 also consider <code>CGI::Lite</code>, which implements a minimal
557 set of functionality, which is all you need in most programs.</p>
559 <p>If you're writing CGI programs in C, there are a variety of
560 options. One of these is the <code>CGIC</code> library, from
561 <a href="http://www.boutell.com/cgic/"
562 >http://www.boutell.com/cgic/</a>.</p>
565 <section id="moreinfo">
566 <title>For more information</title>
568 <p>The current CGI specification is available in the
569 <a href="http://www.ietf.org/rfc/rfc3875">Common Gateway
570 Interface RFC</a>.</p>
572 <p>When you post a question about a CGI problem that you're
573 having, whether to a mailing list, or to a newsgroup, make sure
574 you provide enough information about what happened, what you
575 expected to happen, and how what actually happened was
576 different, what server you're running, what language your CGI
577 program was in, and, if possible, the offending code. This will
578 make finding your problem much simpler.</p>
580 <p>Note that questions about CGI problems should <strong>never</strong>
581 be posted to the Apache bug database unless you are sure you
582 have found a problem in the Apache source code.</p>