]> granicus.if.org Git - apache/blob - docs/manual/howto/cgi.xml
Weeding out some old references. Replacing w3.org/cgi with link to CGI RFC.
[apache] / docs / manual / howto / cgi.xml
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$ -->
5
6 <!--
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
13
14      http://www.apache.org/licenses/LICENSE-2.0
15
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.
21 -->
22
23 <manualpage metafile="cgi.xml.meta">
24   <parentdocument href="./">How-To / Tutorials</parentdocument>
25
26   <title>Apache Tutorial: Dynamic Content with CGI</title>
27
28   <section id="intro">
29     <title>Introduction</title>
30
31     <related>
32       <modulelist>
33         <module>mod_alias</module>
34         <module>mod_cgi</module>
35       </modulelist>
36
37       <directivelist>
38         <directive module="mod_mime">AddHandler</directive>
39         <directive module="core">Options</directive>
40         <directive module="mod_alias">ScriptAlias</directive>
41       </directivelist>
42     </related>
43
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
50     CGI programs.</p>
51   </section>
52
53   <section id="configuring">
54     <title>Configuring Apache to permit CGI</title>
55
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>
59
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
65     may look like this:
66
67     <example>
68       LoadModule cgi_module modules/mod_cgi.so
69     </example></note>
70
71     <section id="scriptalias">
72       <title>ScriptAlias</title>
73
74       <p>The 
75       <directive module="mod_alias">ScriptAlias</directive>
76
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
81       client.</p>
82
83       <p>The <directive module="mod_alias">ScriptAlias</directive>
84       directive looks like:</p>
85
86       <example>
87         ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/
88       </example>
89
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>
106
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>
114     </section>
115
116     <section id="nonscriptalias">
117       <title>CGI outside of ScriptAlias directories</title>
118
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>
130
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> 
138     </section>
139
140     <section id="options">
141       <title>Explicitly using Options to permit CGI execution</title>
142
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
146       directory:</p>
147
148       <example>
149         &lt;Directory /usr/local/apache2/htdocs/somedir&gt;<br />
150         <indent>
151           Options +ExecCGI<br />
152         </indent>
153         &lt;/Directory&gt;
154       </example>
155
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
161       programs:</p>
162
163       <example>
164         AddHandler cgi-script .cgi .pl
165       </example>
166     </section>
167
168     <section id="htaccess">
169       <title>.htaccess files</title>
170
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>
174     </section>
175
176     <section id="userdir">
177       <title>User Directories</title>
178
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>
182
183       <example>
184       &lt;Directory /home/*/public_html&gt;<br/>
185       <indent>
186         Options +ExecCGI<br/>
187         AddHandler cgi-script .cgi<br/>
188       </indent>
189       &lt;/Directory&gt;
190       </example>
191
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>
195
196       <example>
197       &lt;Directory /home/*/public_html/cgi-bin&gt;<br/>
198       <indent>
199         Options ExecCGI<br/>
200         SetHandler cgi-script<br/>
201       </indent>
202       &lt;/Directory&gt;
203       </example>
204
205     </section>
206
207   </section>
208
209   <section id="writing">
210     <title>Writing a CGI program</title>
211
212     <p>There are two main differences between ``regular''
213     programming, and CGI programming.</p>
214
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
218     will look like:</p>
219
220     <example>
221       Content-type: text/html
222     </example>
223
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
228     content.</p>
229
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>
232
233     <section id="firstcgi">
234       <title>Your first CGI program</title>
235
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>
240
241       <example>
242         #!/usr/bin/perl<br />
243         print "Content-type: text/html\n\n";<br />
244         print "Hello, World.";
245       </example>
246
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
257       of it.</p>
258
259       <p>If you open your favorite browser and tell it to get the
260       address</p>
261
262       <example>
263         http://www.example.com/cgi-bin/first.pl
264       </example>
265
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>
270     </section>
271   </section>
272
273   <section id="troubleshoot">
274     <title>But it's still not working!</title>
275
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>
278
279     <dl>
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>
284
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>
291
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>
296
297       <dt>A message saying "Internal Server Error"</dt>
298       <dd>If you check the 
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
305       headers.</dd>
306     </dl>
307
308     <section id="permissions">
309       <title>File permissions</title>
310
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>
318
319       <example>
320         chmod a+x first.pl
321       </example>
322
323       <p>Also, if your program reads from, or writes to, any other
324       files, those files will need to have the correct permissions
325       to permit this.</p>
326
327     </section>
328
329     <section id="pathinformation">
330       <title>Path information and environment</title>
331
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
336       reference.</p>
337
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
343       program.</p>
344
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>
348
349       <example>
350         #!/usr/bin/perl
351       </example>
352
353       <p>Make sure that this is in fact the path to the
354       interpreter.</p>
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.
362       </note>
363     </section>
364
365     <section id="missingenv">
366       <title>Missing environment variables</title>
367
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>
371
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>
378
379     </section>
380
381     <section id="syntaxerrors">
382       <title>Program errors</title>
383
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>
390
391       <example>
392       cd /usr/local/apache2/cgi-bin<br/>
393       ./first.pl
394       </example>
395
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
399       the script.)</p>
400
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
407       details.</p>
408     </section>
409
410     <section id="errorlogs">
411       <title>Error logs</title>
412
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>
420     </section>
421
422     <section id="suexec">
423       <title>Suexec</title>
424
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>
431
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>
436
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>
444     </section>
445   </section>
446
447   <section id="behindscenes">
448     <title>What's going on behind the scenes?</title>
449
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>
456
457     <section id="env">
458       <title>Environment variables</title>
459
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>
467
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>
473
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>
479
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 
483       <code>cgi-bin</code>
484
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>
491
492       <example>
493         #!/usr/bin/perl<br />
494         print "Content-type: text/html\n\n";<br />
495         foreach $key (keys %ENV) {<br />
496         <indent>
497           print "$key --&gt; $ENV{$key}&lt;br&gt;";<br />
498         </indent>
499         }
500       </example>
501     </section>
502
503     <section id="stdin">
504       <title>STDIN and STDOUT</title>
505
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> 
512
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>
518
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       (&amp;). 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
525       something like:</p>
526
527       <example>
528         name=Rich%20Bowen&amp;city=Lexington&amp;state=KY&amp;sidekick=Squirrel%20Monkey
529       </example>
530
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>
538
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>
543     </section>
544   </section>
545
546   <section id="libraries">
547     <title>CGI modules/libraries</title>
548
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>
552
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>
558
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>
563   </section>
564
565   <section id="moreinfo">
566     <title>For more information</title>
567
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>
571
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>
579
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>
583   </section>
584 </manualpage>
585