]> granicus.if.org Git - apache/blob - docs/manual/howto/cgi.xml
Might as well be pedantic while we're at it.
[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     <highlight language="config">
68       LoadModule cgi_module modules/mod_cgi.so
69     </highlight></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       <highlight language="config">
87         ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/
88       </highlight>
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       <highlight language="config">
149 &lt;Directory /usr/local/apache2/htdocs/somedir&gt;
150     Options +ExecCGI
151 &lt;/Directory&gt;
152       </highlight>
153
154       <p>The above directive tells Apache to permit the execution
155       of CGI files. You will also need to tell the server what
156       files are CGI files. The following <directive module="mod_mime"
157       >AddHandler</directive> directive tells the server to treat all
158       files with the <code>cgi</code> or <code>pl</code> extension as CGI
159       programs:</p>
160
161       <highlight language="config">
162         AddHandler cgi-script .cgi .pl
163       </highlight>
164     </section>
165
166     <section id="htaccess">
167       <title>.htaccess files</title>
168
169       <p>The <a href="htaccess.html"><code>.htaccess</code> tutorial</a>
170       shows how to activate CGI programs if you do not have
171       access to <code>httpd.conf</code>.</p>
172     </section>
173
174     <section id="userdir">
175       <title>User Directories</title>
176
177       <p>To allow CGI program execution for any file ending in
178       <code>.cgi</code> in users' directories, you can use the
179       following configuration.</p>
180
181       <highlight language="config">
182 &lt;Directory /home/*/public_html&gt;
183     Options +ExecCGI
184     AddHandler cgi-script .cgi
185 &lt;/Directory&gt;
186       </highlight>
187
188       <p>If you wish designate a <code>cgi-bin</code> subdirectory of
189       a user's directory where everything will be treated as a CGI
190       program, you can use the following.</p>
191
192       <highlight language="config">
193 &lt;Directory /home/*/public_html/cgi-bin&gt;
194     Options ExecCGI
195     SetHandler cgi-script
196 &lt;/Directory&gt;
197       </highlight>
198
199     </section>
200
201   </section>
202
203   <section id="writing">
204     <title>Writing a CGI program</title>
205
206     <p>There are two main differences between ``regular''
207     programming, and CGI programming.</p>
208
209     <p>First, all output from your CGI program must be preceded by
210     a <glossary>MIME-type</glossary> header. This is HTTP header that tells the client
211     what sort of content it is receiving. Most of the time, this
212     will look like:</p>
213
214     <example>
215       Content-type: text/html
216     </example>
217
218     <p>Secondly, your output needs to be in HTML, or some other
219     format that a browser will be able to display. Most of the
220     time, this will be HTML, but occasionally you might write a CGI
221     program that outputs a gif image, or other non-HTML
222     content.</p>
223
224     <p>Apart from those two things, writing a CGI program will look
225     a lot like any other program that you might write.</p>
226
227     <section id="firstcgi">
228       <title>Your first CGI program</title>
229
230       <p>The following is an example CGI program that prints one
231       line to your browser. Type in the following, save it to a
232       file called <code>first.pl</code>, and put it in your
233       <code>cgi-bin</code> directory.</p>
234
235       <highlight language="perl">
236 #!/usr/bin/perl
237 print "Content-type: text/html\r\n\r\n";
238 print "Hello, World.";
239       </highlight>
240
241       <p>Even if you are not familiar with Perl, you should be able
242       to see what is happening here. The first line tells Apache
243       (or whatever shell you happen to be running under) that this
244       program can be executed by feeding the file to the
245       interpreter found at the location <code>/usr/bin/perl</code>.
246       The second line prints the content-type declaration we
247       talked about, followed by two carriage-return newline pairs.
248       This puts a blank line after the header, to indicate the end
249       of the HTTP headers, and the beginning of the body. The third
250       line prints the string "Hello, World.". And that's the end
251       of it.</p>
252
253       <p>If you open your favorite browser and tell it to get the
254       address</p>
255
256       <example>
257         http://www.example.com/cgi-bin/first.pl
258       </example>
259
260       <p>or wherever you put your file, you will see the one line
261       <code>Hello, World.</code> appear in your browser window.
262       It's not very exciting, but once you get that working, you'll
263       have a good chance of getting just about anything working.</p>
264     </section>
265   </section>
266
267   <section id="troubleshoot">
268     <title>But it's still not working!</title>
269
270     <p>There are four basic things that you may see in your browser
271     when you try to access your CGI program from the web:</p>
272
273     <dl>
274       <dt>The output of your CGI program</dt>
275       <dd>Great! That means everything worked fine.  If the output is correct,
276       but the browser is not processing it correctly, make sure you have the
277       correct <code>Content-Type</code> set in your CGI program.</dd>
278
279       <dt>The source code of your CGI program or a "POST Method Not
280       Allowed" message</dt>
281       <dd>That means that you have not properly configured Apache
282       to process your CGI program. Reread the section on
283       <a href="#configuring">configuring
284       Apache</a> and try to find what you missed.</dd>
285
286       <dt>A message starting with "Forbidden"</dt>
287       <dd>That means that there is a permissions problem. Check the
288       <a href="#errorlogs">Apache error log</a> and the section below on
289       <a href="#permissions">file permissions</a>.</dd>
290
291       <dt>A message saying "Internal Server Error"</dt>
292       <dd>If you check the
293       <a href="#errorlogs">Apache error log</a>, you will probably
294       find that it says "Premature end of
295       script headers", possibly along with an error message
296       generated by your CGI program. In this case, you will want to
297       check each of the below sections to see what might be
298       preventing your CGI program from emitting the proper HTTP
299       headers.</dd>
300     </dl>
301
302     <section id="permissions">
303       <title>File permissions</title>
304
305       <p>Remember that the server does not run as you. That is,
306       when the server starts up, it is running with the permissions
307       of an unprivileged user - usually <code>nobody</code>, or
308       <code>www</code> - and so it will need extra permissions to
309       execute files that are owned by you. Usually, the way to give
310       a file sufficient permissions to be executed by <code>nobody</code>
311       is to give everyone execute permission on the file:</p>
312
313       <example>
314         chmod a+x first.pl
315       </example>
316
317       <p>Also, if your program reads from, or writes to, any other
318       files, those files will need to have the correct permissions
319       to permit this.</p>
320
321     </section>
322
323     <section id="pathinformation">
324       <title>Path information and environment</title>
325
326       <p>When you run a program from your command line, you have
327       certain information that is passed to the shell without you
328       thinking about it. For example, you have a <code>PATH</code>,
329       which tells the shell where it can look for files that you
330       reference.</p>
331
332       <p>When a program runs through the web server as a CGI program,
333       it may not have the same <code>PATH</code>. Any programs that you
334       invoke in your CGI program (like <code>sendmail</code>, for
335       example) will need to be specified by a full path, so that the
336       shell can find them when it attempts to execute your CGI
337       program.</p>
338
339       <p>A common manifestation of this is the path to the script
340       interpreter (often <code>perl</code>) indicated in the first
341       line of your CGI program, which will look something like:</p>
342
343       <highlight language="perl">
344         #!/usr/bin/perl
345       </highlight>
346
347       <p>Make sure that this is in fact the path to the
348       interpreter.</p>
349       <note type="warning">
350       When editing CGI scripts on Windows, end-of-line characters may be
351       appended to the interpreter path. Ensure that files are then
352       transferred to the server in ASCII mode. Failure to do so may
353       result in "Command not found" warnings from the OS, due to the
354       unrecognized end-of-line character being interpreted as a part of
355       the interpreter filename.
356       </note>
357     </section>
358
359     <section id="missingenv">
360       <title>Missing environment variables</title>
361
362       <p>If your CGI program depends on non-standard <a
363       href="#env">environment variables</a>, you will need to
364       assure that those variables are passed by Apache.</p>
365
366       <p>When you miss HTTP headers from the environment, make
367       sure they are formatted according to
368       <a href="http://tools.ietf.org/html/rfc2616">RFC 2616</a>,
369       section 4.2: Header names must start with a letter,
370       followed only by letters, numbers or hyphen. Any header
371       violating this rule will be dropped silently.</p>
372
373     </section>
374
375     <section id="syntaxerrors">
376       <title>Program errors</title>
377
378       <p>Most of the time when a CGI program fails, it's because of
379       a problem with the program itself. This is particularly true
380       once you get the hang of this CGI stuff, and no longer make
381       the above two mistakes.  The first thing to do is to make
382       sure that your program runs from the command line before
383       testing it via the web server.  For example, try:</p>
384
385       <example>
386       cd /usr/local/apache2/cgi-bin<br/>
387       ./first.pl
388       </example>
389
390       <p>(Do not call the <code>perl</code> interpreter.  The shell
391       and Apache should find the interpreter using the <a
392       href="#pathinformation">path information</a> on the first line of
393       the script.)</p>
394
395       <p>The first thing you see written by your program should be
396       a set of HTTP headers, including the <code>Content-Type</code>,
397       followed by a blank line.  If you see anything else, Apache will
398       return the <code>Premature end of script headers</code> error if
399       you try to run it through the server. See <a
400       href="#writing">Writing a CGI program</a> above for more
401       details.</p>
402     </section>
403
404     <section id="errorlogs">
405       <title>Error logs</title>
406
407       <p>The error logs are your friend. Anything that goes wrong
408       generates message in the error log. You should always look
409       there first. If the place where you are hosting your web site
410       does not permit you access to the error log, you should
411       probably host your site somewhere else. Learn to read the
412       error logs, and you'll find that almost all of your problems
413       are quickly identified, and quickly solved.</p>
414     </section>
415
416     <section id="suexec">
417       <title>Suexec</title>
418
419       <p>The <a href="../suexec.html">suexec</a> support program
420       allows CGI programs to be run under different user permissions,
421       depending on which virtual host or user home directory they are
422       located in. Suexec has very strict permission checking, and any
423       failure in that checking will result in your CGI programs
424       failing with <code>Premature end of script headers</code>.</p>
425
426       <p>To check if you are using suexec, run <code>apachectl
427       -V</code> and check for the location of <code>SUEXEC_BIN</code>.
428       If Apache finds an <program>suexec</program> binary there on startup,
429       suexec will be activated.</p>
430
431       <p>Unless you fully understand suexec, you should not be using it.
432       To disable suexec, simply remove (or rename) the <program>suexec</program>
433       binary pointed to by <code>SUEXEC_BIN</code> and then restart the
434       server.  If, after reading about <a href="../suexec.html">suexec</a>,
435       you still wish to use it, then run <code>suexec -V</code> to find
436       the location of the suexec log file, and use that log file to
437       find what policy you are violating.</p>
438     </section>
439   </section>
440
441   <section id="behindscenes">
442     <title>What's going on behind the scenes?</title>
443
444     <p>As you become more advanced in CGI programming, it will
445     become useful to understand more about what's happening behind
446     the scenes. Specifically, how the browser and server
447     communicate with one another. Because although it's all very
448     well to write a program that prints "Hello, World.", it's not
449     particularly useful.</p>
450
451     <section id="env">
452       <title>Environment variables</title>
453
454       <p>Environment variables are values that float around you as
455       you use your computer. They are useful things like your path
456       (where the computer searches for the actual file
457       implementing a command when you type it), your username, your
458       terminal type, and so on. For a full list of your normal,
459       every day environment variables, type
460       <code>env</code> at a command prompt.</p>
461
462       <p>During the CGI transaction, the server and the browser
463       also set environment variables, so that they can communicate
464       with one another. These are things like the browser type
465       (Netscape, IE, Lynx), the server type (Apache, IIS, WebSite),
466       the name of the CGI program that is being run, and so on.</p>
467
468       <p>These variables are available to the CGI programmer, and
469       are half of the story of the client-server communication. The
470       complete list of required variables is at
471       <a href="http://www.ietf.org/rfc/rfc3875">Common Gateway
472       Interface RFC</a>.</p>
473
474       <p>This simple Perl CGI program will display all of the
475       environment variables that are being passed around. Two
476       similar programs are included in the
477       <code>cgi-bin</code>
478
479       directory of the Apache distribution. Note that some
480       variables are required, while others are optional, so you may
481       see some variables listed that were not in the official list.
482       In addition, Apache provides many different ways for you to
483       <a href="../env.html">add your own environment variables</a>
484       to the basic ones provided by default.</p>
485
486       <highlight language="perl">
487 #!/usr/bin/perl
488 use strict;
489 use warnings;
490
491 print "Content-type: text/html\r\n\r\n";
492 foreach my $key (keys %ENV) {
493     print "$key --&gt; $ENV{$key}&lt;br&gt;";
494 }
495       </highlight>
496     </section>
497
498     <section id="stdin">
499       <title>STDIN and STDOUT</title>
500
501       <p>Other communication between the server and the client
502       happens over standard input (<code>STDIN</code>) and standard
503       output (<code>STDOUT</code>). In normal everyday context,
504       <code>STDIN</code> means the keyboard, or a file that a
505       program is given to act on, and <code>STDOUT</code>
506       usually means the console or screen.</p>
507
508       <p>When you <code>POST</code> a web form to a CGI program,
509       the data in that form is bundled up into a special format
510       and gets delivered to your CGI program over <code>STDIN</code>.
511       The program then can process that data as though it was
512       coming in from the keyboard, or from a file</p>
513
514       <p>The "special format" is very simple. A field name and
515       its value are joined together with an equals (=) sign, and
516       pairs of values are joined together with an ampersand
517       (&amp;). Inconvenient characters like spaces, ampersands, and
518       equals signs, are converted into their hex equivalent so that
519       they don't gum up the works. The whole data string might look
520       something like:</p>
521
522       <example>
523         name=Rich%20Bowen&amp;city=Lexington&amp;state=KY&amp;sidekick=Squirrel%20Monkey
524       </example>
525
526       <p>You'll sometimes also see this type of string appended to
527       a URL. When that is done, the server puts that string
528       into the environment variable called
529       <code>QUERY_STRING</code>. That's called a <code>GET</code>
530       request. Your HTML form specifies whether a <code>GET</code>
531       or a <code>POST</code> is used to deliver the data, by setting the
532       <code>METHOD</code> attribute in the <code>FORM</code> tag.</p>
533
534       <p>Your program is then responsible for splitting that string
535       up into useful information. Fortunately, there are libraries
536       and modules available to help you process this data, as well
537       as handle other of the aspects of your CGI program.</p>
538     </section>
539   </section>
540
541   <section id="libraries">
542     <title>CGI modules/libraries</title>
543
544     <p>When you write CGI programs, you should consider using a
545     code library, or module, to do most of the grunt work for you.
546     This leads to fewer errors, and faster development.</p>
547
548     <p>If you're writing CGI programs in Perl, modules are
549     available on <a href="http://www.cpan.org/">CPAN</a>. The most
550     popular module for this purpose is <code>CGI.pm</code>. You might
551     also consider <code>CGI::Lite</code>, which implements a minimal
552     set of functionality, which is all you need in most programs.</p>
553
554     <p>If you're writing CGI programs in C, there are a variety of
555     options. One of these is the <code>CGIC</code> library, from
556     <a href="http://www.boutell.com/cgic/"
557     >http://www.boutell.com/cgic/</a>.</p>
558   </section>
559
560   <section id="moreinfo">
561     <title>For more information</title>
562
563     <p>The current CGI specification is available in the
564     <a href="http://www.ietf.org/rfc/rfc3875">Common Gateway
565     Interface RFC</a>.</p>
566
567     <p>When you post a question about a CGI problem that you're
568     having, whether to a mailing list, or to a newsgroup, make sure
569     you provide enough information about what happened, what you
570     expected to happen, and how what actually happened was
571     different, what server you're running, what language your CGI
572     program was in, and, if possible, the offending code. This will
573     make finding your problem much simpler.</p>
574
575     <p>Note that questions about CGI problems should <strong>never</strong>
576     be posted to the Apache bug database unless you are sure you
577     have found a problem in the Apache source code.</p>
578   </section>
579 </manualpage>
580