| Class | CGI |
| In: |
lib/cgi/session.rb
lib/cgi.rb lib/cgi-lib.rb |
| Parent: | Object |
CGI class. See documentation for the file cgi.rb for an overview of the CGI protocol.
CGI is a large class, providing several categories of methods, many of which are mixed in from other modules. Some of the documentation is in this class, some in the modules CGI::QueryExtension and CGI::HtmlExtension. See CGI::Cookie for specific information on handling cookies, and cgi/session.rb (CGI::Session) for information on sessions.
For queries, CGI provides methods to get at environmental variables, parameters, cookies, and multipart request data. For responses, CGI provides methods for writing output and generating HTML.
Read on for more details. Examples are provided at the bottom.
The CGI class dynamically mixes in parameter and cookie-parsing functionality, environmental variable access, and support for parsing multipart requests (including uploaded files) from the CGI::QueryExtension module.
The standard CGI environmental variables are available as read-only attributes of a CGI object. The following is a list of these variables:
AUTH_TYPE HTTP_HOST REMOTE_IDENT CONTENT_LENGTH HTTP_NEGOTIATE REMOTE_USER CONTENT_TYPE HTTP_PRAGMA REQUEST_METHOD GATEWAY_INTERFACE HTTP_REFERER SCRIPT_NAME HTTP_ACCEPT HTTP_USER_AGENT SERVER_NAME HTTP_ACCEPT_CHARSET PATH_INFO SERVER_PORT HTTP_ACCEPT_ENCODING PATH_TRANSLATED SERVER_PROTOCOL HTTP_ACCEPT_LANGUAGE QUERY_STRING SERVER_SOFTWARE HTTP_CACHE_CONTROL REMOTE_ADDR HTTP_FROM REMOTE_HOST
For each of these variables, there is a corresponding attribute with the same name, except all lower case and without a preceding HTTP_. content_length and server_port are integers; the rest are strings.
The method params() returns a hash of all parameters in the request as name/value-list pairs, where the value-list is an Array of one or more values. The CGI object itself also behaves as a hash of parameter names to values, but only returns a single value (as a String) for each parameter name.
For instance, suppose the request contains the parameter "favourite_colours" with the multiple values "blue" and "green". The following behaviour would occur:
cgi.params["favourite_colours"] # => ["blue", "green"] cgi["favourite_colours"] # => "blue"
If a parameter does not exist, the former method will return an empty array, the latter an empty string. The simplest way to test for existence of a parameter is by the has_key? method.
HTTP Cookies are automatically parsed from the request. They are available from the cookies() accessor, which returns a hash from cookie name to CGI::Cookie object.
If a request‘s method is POST and its content type is multipart/form-data, then it may contain uploaded files. These are stored by the QueryExtension module in the parameters of the request. The parameter name is the name attribute of the file input field, as usual. However, the value is not a string, but an IO object, either an IOString for small files, or a Tempfile for larger ones. This object also has the additional singleton methods:
| local_path(): | the path of the uploaded file on the local filesystem |
| original_filename(): | the name of the file on the client computer |
| content_type(): | the content type of the file |
The CGI class provides methods for sending header and content output to the HTTP client, and mixes in methods for programmatic HTML generation from CGI::HtmlExtension and CGI::TagMaker modules. The precise version of HTML to use for HTML generation is specified at object creation time.
The simplest way to send output to the HTTP client is using the out() method. This takes the HTTP headers as a hash parameter, and the body content via a block. The headers can be generated as a string using the header() method. The output stream can be written directly to using the print() method.
Each HTML element has a corresponding method for generating that element as a String. The name of this method is the same as that of the element, all lowercase. The attributes of the element are passed in as a hash, and the body as a no-argument block that evaluates to a String. The HTML generation module knows which elements are always empty, and silently drops any passed-in body. It also knows which elements require matching closing tags and which don‘t. However, it does not know what attributes are legal for which elements.
There are also some additional HTML generation methods mixed in from the CGI::HtmlExtension module. These include individual methods for the different types of form inputs, and methods for elements that commonly take particular attributes where the attributes can be directly specified as arguments, rather than via a hash.
require "cgi"
cgi = CGI.new
value = cgi['field_name'] # <== value string for 'field_name'
# if not 'field_name' included, then return "".
fields = cgi.keys # <== array of field names
# returns true if form has 'field_name'
cgi.has_key?('field_name')
cgi.has_key?('field_name')
cgi.include?('field_name')
CAUTION! cgi[‘field_name’] returned an Array with the old cgi.rb(included in ruby 1.6)
require "cgi" cgi = CGI.new params = cgi.params
cgi.params is a hash.
cgi.params['new_field_name'] = ["value"] # add new param
cgi.params['field_name'] = ["new_value"] # change value
cgi.params.delete('field_name') # delete param
cgi.params.clear # delete all params
require "pstore"
db = PStore.new("query.db")
db.transaction do
db["params"] = cgi.params
end
require "pstore"
db = PStore.new("query.db")
db.transaction do
cgi.params = db["params"]
end
require "cgi" cgi = CGI.new value = cgi['field_name'] # <== value string for 'field_name' value.read # <== body of value value.local_path # <== path to local file of value value.original_filename # <== original filename of value value.content_type # <== content_type of value
and value has StringIO or Tempfile class methods.
require "cgi"
cgi = CGI.new
values = cgi.cookies['name'] # <== array of 'name'
# if not 'name' included, then return [].
names = cgi.cookies.keys # <== array of cookie names
and cgi.cookies is a hash.
require "cgi"
cgi = CGI.new
for name, cookie in cgi.cookies
cookie.expires = Time.now + 30
end
cgi.out("cookie" => cgi.cookies) {"string"}
cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
require "cgi"
cgi = CGI.new
cgi.cookies['name'].expires = Time.now + 30
cgi.out("cookie" => cgi.cookies['name']) {"string"}
require "cgi"
cgi = CGI.new("html3") # add HTML generation methods
cgi.out() do
cgi.html() do
cgi.head{ cgi.title{"TITLE"} } +
cgi.body() do
cgi.form() do
cgi.textarea("get_text") +
cgi.br +
cgi.submit
end +
cgi.pre() do
CGI::escapeHTML(
"params: " + cgi.params.inspect + "\n" +
"cookies: " + cgi.cookies.inspect + "\n" +
ENV.collect() do |key, value|
key + " --> " + value + "\n"
end.join("")
)
end
end
end
end
# add HTML generation methods
CGI.new("html3") # html3.2
CGI.new("html4") # html4.01 (Strict)
CGI.new("html4Tr") # html4.01 Transitional
CGI.new("html4Fr") # html4.01 Frameset
| CR | = | "\015" |
| LF | = | "\012" |
| EOL | = | CR + LF |
| RFC822_DAYS | = | %w[ Sun Mon Tue Wed Thu Fri Sat ] |
| RFC822_MONTHS | = | %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ] |
| cookie | [R] | |
| inputs | [R] |
make raw cookie string
# File lib/cgi-lib.rb, line 211
211: def CGI::cookie(options)
212: "Set-Cookie: " + options['name'] + '=' + escape(options['value']) +
213: (options['domain'] ? '; domain=' + options['domain'] : '') +
214: (options['path'] ? '; path=' + options['path'] : '') +
215: (options['expires'] ? '; expires=' + rfc1123_date(options['expires']) : '') +
216: (options['secure'] ? '; secure' : '')
217: end
URL-encode a string.
url_encoded_string = CGI::escape("'Stop!' said Fred")
# => "%27Stop%21%27+said+Fred"
# File lib/cgi.rb, line 341
341: def CGI::escape(string)
342: string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
343: '%' + $1.unpack('H2' * $1.size).join('%').upcase
344: end.tr(' ', '+')
345: end
Escape only the tags of certain HTML elements in string.
Takes an element or elements or array of elements. Each element is specified by the name of the element, without angle brackets. This matches both the start and the end tag of that element. The attribute list of the open tag will also be escaped (for instance, the double-quotes surrounding attribute values).
print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
# "<BR><A HREF="url"></A>"
print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
# "<BR><A HREF="url"></A>"
# File lib/cgi.rb, line 417
417: def CGI::escapeElement(string, *elements)
418: elements = elements[0] if elements[0].kind_of?(Array)
419: unless elements.empty?
420: string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
421: CGI::escapeHTML($&)
422: end
423: else
424: string
425: end
426: end
Escape special characters in HTML, namely &\"<>
CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo "bar" <baz>"
# File lib/cgi.rb, line 361
361: def CGI::escapeHTML(string)
362: string.gsub(/&/n, '&').gsub(/\"/n, '"').gsub(/>/n, '>').gsub(/</n, '<')
363: end
make HTTP header string
# File lib/cgi-lib.rb, line 220
220: def CGI::header(*options)
221: if defined?(MOD_RUBY)
222: options.each{|option|
223: option.sub(/(.*?): (.*)/){
224: Apache::request.headers_out[$1] = $2
225: }
226: }
227: Apache::request.send_http_header
228: ''
229: else
230: if options.delete("nph") or (ENV['SERVER_SOFTWARE'] =~ /IIS/)
231: [(ENV['SERVER_PROTOCOL'] or "HTTP/1.0") + " 200 OK",
232: "Date: " + rfc1123_date(Time.now),
233: "Server: " + (ENV['SERVER_SOFTWARE'] or ""),
234: "Connection: close"] +
235: (options.empty? ? ["Content-Type: text/html"] : options)
236: else
237: options.empty? ? ["Content-Type: text/html"] : options
238: end.join(EOL) + EOL + EOL
239: end
240: end
# File lib/cgi-lib.rb, line 248
248: def CGI::message(message, title = "", header = ["Content-Type: text/html"])
249: if message.kind_of?(Hash)
250: title = message['title']
251: header = message['header']
252: message = message['body']
253: end
254: CGI::print(*header){
255: CGI::tag("HTML"){
256: CGI::tag("HEAD"){ CGI.tag("TITLE"){ title } } +
257: CGI::tag("BODY"){ message }
258: }
259: }
260: true
261: end
# File lib/cgi-lib.rb, line 162
162: def initialize(input = $stdin)
163:
164: @inputs = {}
165: @cookie = {}
166:
167: case ENV['REQUEST_METHOD']
168: when "GET"
169: ENV['QUERY_STRING'] or ""
170: when "POST"
171: input.read(Integer(ENV['CONTENT_LENGTH'])) or ""
172: else
173: read_from_cmdline
174: end.split(/[&;]/).each do |x|
175: key, val = x.split(/=/,2).collect{|x|CGI::unescape(x)}
176: if @inputs.include?(key)
177: @inputs[key] += "\0" + (val or "")
178: else
179: @inputs[key] = (val or "")
180: end
181: end
182:
183: super(@inputs)
184:
185: if ENV.has_key?('HTTP_COOKIE') or ENV.has_key?('COOKIE')
186: (ENV['HTTP_COOKIE'] or ENV['COOKIE']).split(/; /).each do |x|
187: key, val = x.split(/=/,2)
188: key = CGI::unescape(key)
189: val = val.split(/&/).collect{|x|CGI::unescape(x)}.join("\0")
190: if @cookie.include?(key)
191: @cookie[key] += "\0" + val
192: else
193: @cookie[key] = val
194: end
195: end
196: end
197: end
type specifies which version of HTML to load the HTML generation methods for. The following versions of HTML are supported:
| html3: | HTML 3.x |
| html4: | HTML 4.0 |
| html4Tr: | HTML 4.0 Transitional |
| html4Fr: | HTML 4.0 with Framesets |
If not specified, no HTML generation methods will be loaded.
If the CGI object is not created in a standard CGI call environment (that is, it can‘t locate REQUEST_METHOD in its environment), then it will run in "offline" mode. In this mode, it reads its parameters from the command line or (failing that) from standard input. Otherwise, cookies and other parameters are parsed automatically from the standard CGI locations, which varies according to the REQUEST_METHOD.
# File lib/cgi.rb, line 2299
2299: def initialize(type = "query")
2300: if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
2301: Apache.request.setup_cgi_env
2302: end
2303:
2304: extend QueryExtension
2305: @multipart = false
2306: if defined?(CGI_PARAMS)
2307: warn "do not use CGI_PARAMS and CGI_COOKIES"
2308: @params = CGI_PARAMS.dup
2309: @cookies = CGI_COOKIES.dup
2310: else
2311: initialize_query() # set @params, @cookies
2312: end
2313: @output_cookies = nil
2314: @output_hidden = nil
2315:
2316: case type
2317: when "html3"
2318: extend Html3
2319: element_init()
2320: extend HtmlExtension
2321: when "html4"
2322: extend Html4
2323: element_init()
2324: extend HtmlExtension
2325: when "html4Tr"
2326: extend Html4Tr
2327: element_init()
2328: extend HtmlExtension
2329: when "html4Fr"
2330: extend Html4Tr
2331: element_init()
2332: extend Html4Fr
2333: element_init()
2334: extend HtmlExtension
2335: end
2336: end
Parse an HTTP query string into a hash of key=>value pairs.
params = CGI::parse("query_string")
# {"name1" => ["value1", "value2", ...],
# "name2" => ["value1", "value2", ...], ... }
# File lib/cgi.rb, line 900
900: def CGI::parse(query)
901: params = Hash.new([].freeze)
902:
903: query.split(/[&;]/n).each do |pairs|
904: key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
905: if params.has_key?(key)
906: params[key].push(value)
907: else
908: params[key] = [value]
909: end
910: end
911:
912: params
913: end
Prettify (indent) an HTML string.
string is the HTML string to indent. shift is the indentation unit to use; it defaults to two spaces.
print CGI::pretty("<HTML><BODY></BODY></HTML>")
# <HTML>
# <BODY>
# </BODY>
# </HTML>
print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
# <HTML>
# <BODY>
# </BODY>
# </HTML>
# File lib/cgi.rb, line 1226
1226: def CGI::pretty(string, shift = " ")
1227: lines = string.gsub(/(?!\A)<(?:.|\n)*?>/n, "\n\\0").gsub(/<(?:.|\n)*?>(?!\n)/n, "\\0\n")
1228: end_pos = 0
1229: while end_pos = lines.index(/^<\/(\w+)/n, end_pos)
1230: element = $1.dup
1231: start_pos = lines.rindex(/^\s*<#{element}/ni, end_pos)
1232: lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/n, "\n" + shift) + "__"
1233: end
1234: lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/n, '\1')
1235: end
Format a Time object as a String using the format specified by RFC 1123.
CGI::rfc1123_date(Time.now)
# Sat, 01 Jan 2000 00:00:00 GMT
# File lib/cgi.rb, line 454
454: def CGI::rfc1123_date(time)
455: t = time.clone.gmtime
456: return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
457: RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
458: t.hour, t.min, t.sec)
459: end
make rfc1123 date string
# File lib/cgi-lib.rb, line 126
126: def CGI::rfc1123_date(time)
127: t = time.clone.gmtime
128: return format("%s, %.2d %s %d %.2d:%.2d:%.2d GMT",
129: RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
130: t.hour, t.min, t.sec)
131: end
make HTML tag string
# File lib/cgi-lib.rb, line 203
203: def CGI::tag(element, attributes = {})
204: "<" + escapeHTML(element) + attributes.collect{|name, value|
205: " " + escapeHTML(name) + '="' + escapeHTML(value) + '"'
206: }.to_s + ">" +
207: (iterator? ? yield.to_s + "</" + escapeHTML(element) + ">" : "")
208: end
URL-decode a string.
string = CGI::unescape("%27Stop%21%27+said+Fred")
# => "'Stop!' said Fred"
# File lib/cgi.rb, line 351
351: def CGI::unescape(string)
352: string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
353: [$1.delete('%')].pack('H*')
354: end
355: end
Undo escaping such as that done by CGI::escapeElement()
print CGI::unescapeElement(
CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
# "<BR><A HREF="url"></A>"
print CGI::unescapeElement(
CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
# "<BR><A HREF="url"></A>"
# File lib/cgi.rb, line 438
438: def CGI::unescapeElement(string, *elements)
439: elements = elements[0] if elements[0].kind_of?(Array)
440: unless elements.empty?
441: string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
442: CGI::unescapeHTML($&)
443: end
444: else
445: string
446: end
447: end
Unescape a string that has been HTML-escaped
CGI::unescapeHTML("Usage: foo "bar" <baz>")
# => "Usage: foo \"bar\" <baz>"
# File lib/cgi.rb, line 369
369: def CGI::unescapeHTML(string)
370: string.gsub(/&(amp|quot|gt|lt|\#[0-9]+|\#x[0-9A-Fa-f]+);/n) do
371: match = $1.dup
372: case match
373: when 'amp' then '&'
374: when 'quot' then '"'
375: when 'gt' then '>'
376: when 'lt' then '<'
377: when /\A#0*(\d+)\z/n then
378: if Integer($1) < 256
379: Integer($1).chr
380: else
381: if Integer($1) < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
382: [Integer($1)].pack("U")
383: else
384: "&##{$1};"
385: end
386: end
387: when /\A#x([0-9a-f]+)\z/ni then
388: if $1.hex < 128
389: $1.hex.chr
390: else
391: if $1.hex < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
392: [$1.hex].pack("U")
393: else
394: "&#x#{$1};"
395: end
396: end
397: else
398: "&#{match};"
399: end
400: end
401: end
Create an HTTP header block as a string.
Includes the empty line that ends the header block.
options can be a string specifying the Content-Type (defaults to text/html), or a hash of header key/value pairs. The following header keys are recognized:
| type: | the Content-Type header. Defaults to "text/html" |
| charset: | the charset of the body, appended to the Content-Type header. |
| nph: | a boolean value. If true, prepend protocol string and status code, and date; and sets default values for "server" and "connection" if not explicitly set. |
| status: | the HTTP status code, returned as the Status header. See the list of available status codes below. |
| server: | the server software, returned as the Server header. |
| connection: | the connection type, returned as the Connection header (for instance, "close". |
| length: | the length of the content that will be sent, returned as the Content-Length header. |
| language: | the language of the content, returned as the Content-Language header. |
| expires: | the time on which the current content expires, as a Time object, returned as the Expires header. |
| cookie: | a cookie or cookies, returned as one or more Set-Cookie headers. The value can be the literal string of the cookie; a CGI::Cookie object; an Array of literal cookie strings or Cookie objects; or a hash all of whose values are literal cookie strings or Cookie objects. These cookies are in addition to the cookies held in the @output_cookies field. |
Other header lines can also be set; they are appended as key: value.
header
# Content-Type: text/html
header("text/plain")
# Content-Type: text/plain
header("nph" => true,
"status" => "OK", # == "200 OK"
# "status" => "200 GOOD",
"server" => ENV['SERVER_SOFTWARE'],
"connection" => "close",
"type" => "text/html",
"charset" => "iso-2022-jp",
# Content-Type: text/html; charset=iso-2022-jp
"length" => 103,
"language" => "ja",
"expires" => Time.now + 30,
"cookie" => [cookie1, cookie2],
"my_header1" => "my_value"
"my_header2" => "my_value")
The status codes are:
"OK" --> "200 OK" "PARTIAL_CONTENT" --> "206 Partial Content" "MULTIPLE_CHOICES" --> "300 Multiple Choices" "MOVED" --> "301 Moved Permanently" "REDIRECT" --> "302 Found" "NOT_MODIFIED" --> "304 Not Modified" "BAD_REQUEST" --> "400 Bad Request" "AUTH_REQUIRED" --> "401 Authorization Required" "FORBIDDEN" --> "403 Forbidden" "NOT_FOUND" --> "404 Not Found" "METHOD_NOT_ALLOWED" --> "405 Method Not Allowed" "NOT_ACCEPTABLE" --> "406 Not Acceptable" "LENGTH_REQUIRED" --> "411 Length Required" "PRECONDITION_FAILED" --> "412 Precondition Failed" "SERVER_ERROR" --> "500 Internal Server Error" "NOT_IMPLEMENTED" --> "501 Method Not Implemented" "BAD_GATEWAY" --> "502 Bad Gateway" "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates"
This method does not perform charset conversion.
# File lib/cgi.rb, line 539
539: def header(options = "text/html")
540:
541: buf = ""
542:
543: case options
544: when String
545: options = { "type" => options }
546: when Hash
547: options = options.dup
548: end
549:
550: unless options.has_key?("type")
551: options["type"] = "text/html"
552: end
553:
554: if options.has_key?("charset")
555: options["type"] += "; charset=" + options.delete("charset")
556: end
557:
558: options.delete("nph") if defined?(MOD_RUBY)
559: if options.delete("nph") or
560: (/IIS\/(\d+)/n.match(env_table['SERVER_SOFTWARE']) and $1.to_i < 5)
561: buf += (env_table["SERVER_PROTOCOL"] or "HTTP/1.0") + " " +
562: (HTTP_STATUS[options["status"]] or options["status"] or "200 OK") +
563: EOL +
564: "Date: " + CGI::rfc1123_date(Time.now) + EOL
565:
566: unless options.has_key?("server")
567: options["server"] = (env_table['SERVER_SOFTWARE'] or "")
568: end
569:
570: unless options.has_key?("connection")
571: options["connection"] = "close"
572: end
573:
574: options.delete("status")
575: end
576:
577: if options.has_key?("status")
578: buf += "Status: " +
579: (HTTP_STATUS[options["status"]] or options["status"]) + EOL
580: options.delete("status")
581: end
582:
583: if options.has_key?("server")
584: buf += "Server: " + options.delete("server") + EOL
585: end
586:
587: if options.has_key?("connection")
588: buf += "Connection: " + options.delete("connection") + EOL
589: end
590:
591: buf += "Content-Type: " + options.delete("type") + EOL
592:
593: if options.has_key?("length")
594: buf += "Content-Length: " + options.delete("length").to_s + EOL
595: end
596:
597: if options.has_key?("language")
598: buf += "Content-Language: " + options.delete("language") + EOL
599: end
600:
601: if options.has_key?("expires")
602: buf += "Expires: " + CGI::rfc1123_date( options.delete("expires") ) + EOL
603: end
604:
605: if options.has_key?("cookie")
606: if options["cookie"].kind_of?(String) or
607: options["cookie"].kind_of?(Cookie)
608: buf += "Set-Cookie: " + options.delete("cookie").to_s + EOL
609: elsif options["cookie"].kind_of?(Array)
610: options.delete("cookie").each{|cookie|
611: buf += "Set-Cookie: " + cookie.to_s + EOL
612: }
613: elsif options["cookie"].kind_of?(Hash)
614: options.delete("cookie").each_value{|cookie|
615: buf += "Set-Cookie: " + cookie.to_s + EOL
616: }
617: end
618: end
619: if @output_cookies
620: for cookie in @output_cookies
621: buf += "Set-Cookie: " + cookie.to_s + EOL
622: end
623: end
624:
625: options.each{|key, value|
626: buf += key + ": " + value.to_s + EOL
627: }
628:
629: if defined?(MOD_RUBY)
630: table = Apache::request.headers_out
631: buf.scan(/([^:]+): (.+)#{EOL}/n){ |name, value|
632: warn sprintf("name:%s value:%s\n", name, value) if $DEBUG
633: case name
634: when 'Set-Cookie'
635: table.add(name, value)
636: when /^status$/ni
637: Apache::request.status_line = value
638: Apache::request.status = value.to_i
639: when /^content-type$/ni
640: Apache::request.content_type = value
641: when /^content-encoding$/ni
642: Apache::request.content_encoding = value
643: when /^location$/ni
644: if Apache::request.status == 200
645: Apache::request.status = 302
646: end
647: Apache::request.headers_out[name] = value
648: else
649: Apache::request.headers_out[name] = value
650: end
651: }
652: Apache::request.send_http_header
653: ''
654: else
655: buf + EOL
656: end
657:
658: end
Print an HTTP header and body to $DEFAULT_OUTPUT ($>)
The header is provided by options, as for header(). The body of the document is that returned by the passed- in block. This block takes no arguments. It is required.
cgi = CGI.new
cgi.out{ "string" }
# Content-Type: text/html
# Content-Length: 6
#
# string
cgi.out("text/plain") { "string" }
# Content-Type: text/plain
# Content-Length: 6
#
# string
cgi.out("nph" => true,
"status" => "OK", # == "200 OK"
"server" => ENV['SERVER_SOFTWARE'],
"connection" => "close",
"type" => "text/html",
"charset" => "iso-2022-jp",
# Content-Type: text/html; charset=iso-2022-jp
"language" => "ja",
"expires" => Time.now + (3600 * 24 * 30),
"cookie" => [cookie1, cookie2],
"my_header1" => "my_value",
"my_header2" => "my_value") { "string" }
Content-Length is automatically calculated from the size of the String returned by the content block.
If ENV[‘REQUEST_METHOD’] == "HEAD", then only the header is outputted (the content block is still required, but it is ignored).
If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then the content is converted to this charset, and the language is set to "ja".
# File lib/cgi.rb, line 703
703: def out(options = "text/html") # :yield:
704:
705: options = { "type" => options } if options.kind_of?(String)
706: content = yield
707:
708: if options.has_key?("charset")
709: require "nkf"
710: case options["charset"]
711: when /iso-2022-jp/ni
712: content = NKF::nkf('-m0 -x -j', content)
713: options["language"] = "ja" unless options.has_key?("language")
714: when /euc-jp/ni
715: content = NKF::nkf('-m0 -x -e', content)
716: options["language"] = "ja" unless options.has_key?("language")
717: when /shift_jis/ni
718: content = NKF::nkf('-m0 -x -s', content)
719: options["language"] = "ja" unless options.has_key?("language")
720: end
721: end
722:
723: options["length"] = content.length.to_s
724: output = stdoutput
725: output.binmode if defined? output.binmode
726: output.print header(options)
727: output.print content unless "HEAD" == env_table['REQUEST_METHOD']
728: end
Print an argument or list of arguments to the default output stream
cgi = CGI.new cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print
# File lib/cgi.rb, line 735
735: def print(*options)
736: stdoutput.print(*options)
737: end
offline mode. read name=value pairs on standard input.
# File lib/cgi-lib.rb, line 149
149: def read_from_cmdline
150: require "shellwords.rb"
151: words = Shellwords.shellwords(
152: if not ARGV.empty?
153: ARGV.join(' ')
154: else
155: STDERR.print "(offline mode: enter name=value pairs on standard input)\n" if STDIN.tty?
156: readlines.join(' ').gsub(/\n/, '')
157: end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26'))
158:
159: if words.find{|x| x =~ /=/} then words.join('&') else words.join('+') end
160: end