什麼是CGI
CGI 目前由NCSA維護,NCSA定義CGI如下:
CGI(Common Gateway Interface),通用網關接口,它是一段程式,運作在伺服器上如:HTTP伺服器,提供同用戶端HTML頁面的接口。
網頁浏覽
為了更好的了解CGI是如何工作的,我們可以從在網頁上點選一個連結或URL的流程:
- 1、使用你的浏覽器通路URL并連接配接到HTTP web 伺服器。
- 2、Web伺服器接收到請求資訊後會解析URL,并查找通路的檔案在伺服器上是否存在,如果存在傳回檔案的内容,否則傳回錯誤資訊。
- 3、浏覽器從伺服器上接收資訊,并顯示接收的檔案或者錯誤資訊。
CGI程式可以是Python腳本,PERL腳本,SHELL腳本,C或者C++程式等。
CGI架構圖
Web伺服器支援及配置
在你進行CGI程式設計前,確定您的Web伺服器支援CGI及已經配置了CGI的處理程式。
Apache 支援CGI 配置:
設定好CGI目錄:
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
所有的HTTP伺服器執行CGI程式都儲存在一個預先配置的目錄。這個目錄被稱為CGI目錄,并按照慣例,它被命名為/var/www/cgi-bin目錄。
CGI檔案的擴充名為.cgi,python也可以使用.py擴充名。
預設情況下,Linux伺服器配置運作的cgi-bin目錄中為/var/www。
如果你想指定其他運作CGI腳本的目錄,可以修改httpd.conf配置檔案,如下所示:
<Directory "/var/www/cgi-bin">
AllowOverride None
Options +ExecCGI
Order allow,deny
Allow from all
</Directory>
在 AddHandler 中添加 .py 字尾,這樣我們就可以通路 .py 結尾的 python 腳本檔案:
AddHandler cgi-script .cgi .pl .py
第一個CGI程式
我們使用Python建立第一個CGI程式,檔案名為hello.py,檔案位于/var/www/cgi-bin目錄中,内容如下:
#!/usr/bin/python3
print ("Content-type:text/html")
print () # 空行,告訴伺服器結束頭部
print ('<html>')
print ('<head>')
print ('<meta charset="utf-8">')
print ('<title>Hello Word - 我的第一個 CGI 程式!</title>')
print ('</head>')
print ('<body>')
print ('<h2>Hello Word! 我是來自碼農教程的第一CGI程式</h2>')
print ('</body>')
print ('</html>')
檔案儲存後修改 hello.py,修改檔案權限為 755:
chmod 755 hello.py
這個的hello.py腳本是一個簡單的Python腳本,腳本第一行的輸出内容"Content-type:text/html"發送到浏覽器并告知浏覽器顯示的内容類型為"text/html"。
用 print 輸出一個空行用于告訴伺服器結束頭部資訊。
HTTP頭部
hello.py檔案内容中的" Content-type:text/html"即為HTTP頭部的一部分,它會發送給浏覽器告訴浏覽器檔案的内容類型。
HTTP頭部的格式如下:
HTTP 字段名: 字段内容
例如:
Content-type: text/html
以下表格介紹了CGI程式中HTTP頭部經常使用的資訊:
頭 | 描述 |
---|---|
Content-type: | 請求的與實體對應的MIME資訊。例如: Content-type:text/html |
Expires: Date | 響應過期的日期和時間 |
Location: URL | 用來重定向接收方到非請求URL的位置來完成請求或辨別新的資源 |
Last-modified: Date | 請求資源的最後修改時間 |
Content-length: N | 請求的内容長度 |
Set-Cookie: String | 設定Http Cookie |
CGI環境變量
所有的CGI程式都接收以下的環境變量,這些變量在CGI程式中發揮了重要的作用:
變量名 | 描述 |
---|---|
CONTENT_TYPE | 這個環境變量的值訓示所傳遞來的資訊的MIME類型。目前,環境變量CONTENT_TYPE一般都是:application/x-www-form-urlencoded,他表示資料來自于HTML表單。 |
CONTENT_LENGTH | 如果伺服器與CGI程式資訊的傳遞方式是POST,這個環境變量即使從标準輸入STDIN中可以讀到的有效資料的位元組數。這個環境變量在讀取所輸入的資料時必須使用。 |
HTTP_COOKIE | 客戶機内的 COOKIE 内容。 |
HTTP_USER_AGENT | 提供包含了版本數或其他專有資料的客戶浏覽器資訊。 |
PATH_INFO | 這個環境變量的值表示緊接在CGI程式名之後的其他路徑資訊。它常常作為CGI程式的參數出現。 |
QUERY_STRING | 如果伺服器與CGI程式資訊的傳遞方式是GET,這個環境變量的值即使所傳遞的資訊。這個資訊經跟在CGI程式名的後面,兩者中間用一個問号'?'分隔。 |
REMOTE_ADDR | 這個環境變量的值是發送請求的客戶機的IP位址,例如上面的192.168.1.67。這個值總是存在的。而且它是Web客戶機需要提供給Web伺服器的唯一辨別,可以在CGI程式中用它來區分不同的Web客戶機。 |
REMOTE_HOST | 這個環境變量的值包含發送CGI請求的客戶機的主機名。如果不支援你想查詢,則無需定義此環境變量。 |
REQUEST_METHOD | 提供腳本被調用的方法。對于使用 HTTP/1.0 協定的腳本,僅 GET 和 POST 有意義。 |
SCRIPT_FILENAME | CGI腳本的完整路徑 |
SCRIPT_NAME | CGI腳本的的名稱 |
SERVER_NAME | 這是你的 WEB 伺服器的主機名、别名或IP位址。 |
SERVER_SOFTWARE | 這個環境變量的值包含了調用CGI程式的HTTP伺服器的名稱和版本号。例如,上面的值為Apache/2.2.14(Unix) |
以下是一個簡單的CGI腳本輸出CGI的環境變量:
#!/usr/bin/python3
import os
print ("Content-type: text/html")
print ()
print ("<meta charset=\"utf-8\">")
print ("<b>環境變量</b><br>")
print ("<ul>")
for key in os.environ.keys():
print ("<li><span style='color:green'>%30s </span> : %s </li>" % (key,os.environ[key]))
print ("</ul>")
GET和POST方法
浏覽器用戶端通過兩種方法向伺服器傳遞資訊,這兩種方法就是 GET 方法和 POST 方法。
使用GET方法傳輸資料
GET方法發送編碼後的使用者資訊到服務端,資料資訊包含在請求頁面的URL上,以"?"号分割, 如下所示:
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
有關 GET 請求的其他一些注釋:
- GET 請求可被緩存
- GET 請求保留在浏覽器曆史記錄中
- GET 請求可被收藏為書簽
- GET 請求不應在處理敏感資料時使用
- GET 請求有長度限制
- GET 請求隻應當用于取回資料
簡單的url執行個體:GET方法
以下是一個簡單的URL,使用GET方法向hello_get.py程式發送兩個參數:
/cgi-bin/test.py?name=碼農教程&url=http://www.codercto.com
以下為hello_get.py檔案的代碼:
#!/usr/bin/python3
# CGI處理子產品
import cgi, cgitb
# 建立 FieldStorage 的執行個體化
form = cgi.FieldStorage()
# 擷取資料
site_name = form.getvalue('name')
site_url = form.getvalue('url')
print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>碼農教程 CGI 測試執行個體</title>")
print ("</head>")
print ("<body>")
print ("<h2>%s官網:%s</h2>" % (site_name, site_url))
print ("</body>")
print ("</html>")
檔案儲存後修改 hello_get.py,修改檔案權限為 755:
chmod 755 hello_get.py
簡單的表單執行個體:GET方法
以下是一個通過HTML的表單使用GET方法向伺服器發送兩個資料,送出的伺服器腳本同樣是hello_get.py檔案,hello_get.html 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<form action="/cgi-bin/hello_get.py" method="get">
站點名稱: <input type="text" name="name"> <br />
站點 URL: <input type="text" name="url" />
<input type="submit" value="送出" />
</form>
</body>
</html>
預設情況下 cgi-bin 目錄隻能存放腳本檔案,我們将 hello_get.html 存儲在 test 目錄下,修改檔案權限為 755:
chmod 755 hello_get.html
使用POST方法傳遞資料
使用POST方法向伺服器傳遞資料是更安全可靠的,像一些敏感資訊如使用者密碼等需要使用POST傳輸資料。
以下同樣是hello_get.py ,它也可以處理浏覽器送出的POST表單資料:
#!/usr/bin/python3
# CGI處理子產品
import cgi, cgitb
# 建立 FieldStorage 的執行個體化
form = cgi.FieldStorage()
# 擷取資料
site_name = form.getvalue('name')
site_url = form.getvalue('url')
print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>碼農教程 CGI 測試執行個體</title>")
print ("</head>")
print ("<body>")
print ("<h2>%s官網:%s</h2>" % (site_name, site_url))
print ("</body>")
print ("</html>")
以下為表單通過POST方法(method="post")向伺服器腳本 hello_get.py 送出資料:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<form action="/cgi-bin/hello_get.py" method="post">
站點名稱: <input type="text" name="name"> <br />
站點 URL: <input type="text" name="url" />
<input type="submit" value="送出" />
</form>
</body>
</html>
</form>
通過CGI程式傳遞checkbox資料
checkbox用于送出一個或者多個選項資料,HTML代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<form action="/cgi-bin/checkbox.py" method="POST" target="_blank">
<input type="checkbox" name="codercto" value="on" /> 碼農教程
<input type="checkbox" name="google" value="on" /> Google
<input type="submit" value="選擇站點" />
</form>
</body>
</html>
以下為 checkbox.py 檔案的代碼:
#!/usr/bin/python3
# 引入 CGI 處理子產品
import cgi, cgitb
# 建立 FieldStorage的執行個體
form = cgi.FieldStorage()
# 接收字段資料
if form.getvalue('google'):
google_flag = "是"
else:
google_flag = "否"
if form.getvalue('codercto'):
codercto_flag = "是"
else:
codercto_flag = "否"
print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>碼農教程 CGI 測試執行個體</title>")
print ("</head>")
print ("<body>")
print ("<h2> 碼農教程是否選擇了 : %s</h2>" % codercto_flag)
print ("<h2> Google 是否選擇了 : %s</h2>" % google_flag)
print ("</body>")
print ("</html>")
修改 checkbox.py 權限:
chmod 755 checkbox.py
通過CGI程式傳遞Radio資料
Radio 隻向伺服器傳遞一個資料,HTML代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<form action="/cgi-bin/radiobutton.py" method="post" target="_blank">
<input type="radio" name="site" value="codercto" /> 碼農教程
<input type="radio" name="site" value="google" /> Google
<input type="submit" value="送出" />
</form>
</body>
</html>
radiobutton.py 腳本代碼如下:
#!/usr/bin/python3
# 引入 CGI 處理子產品
import cgi, cgitb
# 建立 FieldStorage的執行個體
form = cgi.FieldStorage()
# 接收字段資料
if form.getvalue('site'):
site = form.getvalue('site')
else:
site = "送出資料為空"
print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>碼農教程 CGI 測試執行個體</title>")
print ("</head>")
print ("<body>")
print ("<h2> 選中的網站是 %s</h2>" % site)
print ("</body>")
print ("</html>")
修改 radiobutton.py 權限:
chmod 755 radiobutton.py
通過CGI程式傳遞 Textarea 資料
Textarea 向伺服器傳遞多行資料,HTML代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<form action="/cgi-bin/textarea.py" method="post" target="_blank">
<textarea name="textcontent" cols="40" rows="4">
在這裡輸入内容...
</textarea>
<input type="submit" value="送出" />
</form>
</body>
</html>
textarea.py 腳本代碼如下:
#!/usr/bin/python3
# 引入 CGI 處理子產品
import cgi, cgitb
# 建立 FieldStorage的執行個體
form = cgi.FieldStorage()
# 接收字段資料
if form.getvalue('textcontent'):
text_content = form.getvalue('textcontent')
else:
text_content = "沒有内容"
print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>碼農教程 CGI 測試執行個體</title>")
print ("</head>")
print ("<body>")
print ("<h2> 輸入的内容是:%s</h2>" % text_content)
print ("</body>")
print ("</html>")
修改 textarea.py 權限:
chmod 755 textarea.py
通過CGI程式傳遞下拉資料。
HTML 下拉框代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<form action="/cgi-bin/dropdown.py" method="post" target="_blank">
<select name="dropdown">
<option value="codercto" selected>碼農教程</option>
<option value="google">Google</option>
</select>
<input type="submit" value="送出"/>
</form>
</body>
</html>
dropdown.py 腳本代碼如下所示:
#!/usr/bin/python3
# 引入 CGI 處理子產品
import cgi, cgitb
# 建立 FieldStorage的執行個體
form = cgi.FieldStorage()
# 接收字段資料
if form.getvalue('dropdown'):
dropdown_value = form.getvalue('dropdown')
else:
dropdown_value = "沒有内容"
print ("Content-type:text/html")
print ()
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>碼農教程 CGI 測試執行個體</title>")
print ("</head>")
print ("<body>")
print ("<h2> 選中的選項是:%s</h2>" % dropdown_value)
print ("</body>")
print ("</html>")
修改 dropdown.py 權限:
chmod 755 dropdown.py
CGI中使用Cookie
在 http 協定一個很大的缺點就是不對使用者身份的進行判斷,這樣給程式設計人員帶來很大的不便, 而 cookie 功能的出現彌補了這個不足。
cookie 就是在客戶通路腳本的同時,通過客戶的浏覽器,在客戶硬碟上寫入紀錄資料 ,當下次客戶通路腳本時取回資料資訊,進而達到身份判别的功能,cookie 常用在身份校驗中。
cookie的文法
http cookie的發送是通過http頭部來實作的,他早于檔案的傳遞,頭部set-cookie的文法如下:
Set-cookie:name=name;expires=date;path=path;domain=domain;secure
- name=name: 需要設定cookie的值(name不能使用";"和","号),有多個name值時用 ";" 分隔,例如:name1=name1;name2=name2;name3=name3。
- expires=date: cookie的有效期限,格式: expires="Wdy,DD-Mon-YYYY HH:MM:SS"
- path=path: 設定cookie支援的路徑,如果path是一個路徑,則cookie對這個目錄下的所有檔案及子目錄生效,例如: path="/cgi-bin/",如果path是一個檔案,則cookie指對這個檔案生效,例如:path="/cgi-bin/cookie.cgi"。
- domain=domain: 對cookie生效的域名,例如:domain="www.codercto.com"
- secure: 如果給出此标志,表示cookie隻能通過SSL協定的https伺服器來傳遞。
- cookie的接收是通過設定環境變量HTTP_COOKIE來實作的,CGI程式可以通過檢索該變量擷取cookie資訊。
Cookie設定
Cookie的設定非常簡單,cookie會在http頭部單獨發送。以下執行個體在cookie中設定了name 和 expires:
#!/usr/bin/python3
#
print ('Content-Type: text/html')
print ('Set-Cookie: name="碼農教程";expires=Wed, 28 Aug 2016 18:30:00 GMT')
print ()
print ("""
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<h1>Cookie set OK!</h1>
</body>
</html>
""")
将以上代碼儲存到 cookie_set.py,并修改 cookie_set.py 權限:
chmod 755 cookie_set.py
以上執行個體使用了 Set-Cookie 頭資訊來設定Cookie資訊,可選項中設定了Cookie的其他屬性,如過期時間Expires,域名Domain,路徑Path。這些資訊設定在 "Content-type:text/html"之前。
檢索Cookie資訊
Cookie資訊檢索頁非常簡單,Cookie資訊存儲在CGI的環境變量HTTP_COOKIE中,存儲格式如下:
key1=value1;key2=value2;key3=value3....
以下是一個簡單的CGI檢索cookie資訊的程式:
#!/usr/bin/python3
# 導入子產品
import os
import http.cookies
print ("Content-type: text/html")
print ()
print ("""
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<h1>讀取cookie資訊</h1>
""")
if 'HTTP_COOKIE' in os.environ:
cookie_string=os.environ.get('HTTP_COOKIE')
c= http.cookies.SimpleCookie()
# c=Cookie.SimpleCookie()
c.load(cookie_string)
try:
data=c['name'].value
print ("cookie data: "+data+"<br>")
except KeyError:
print ("cookie 沒有設定或者已過去<br>")
print ("""
</body>
</html>
""")
将以上代碼儲存到 cookie_get.py,并修改 cookie_get.py 權限:
chmod 755 cookie_get.py
以上 cookie 設定顔色 Gif 如下所示:
檔案上傳執行個體
HTML設定上傳檔案的表單需要設定 enctype 屬性為 multipart/form-data,代碼如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<form enctype="multipart/form-data"
action="/cgi-bin/save_file.py" method="post">
<p>選中檔案: <input type="file" name="filename" /></p>
<p><input type="submit" value="上傳" /></p>
</form>
</body>
</html>
save_file.py腳本檔案代碼如下:
#!/usr/bin/python3
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# 擷取檔案名
fileitem = form['filename']
# 檢測檔案是否上傳
if fileitem.filename:
# 設定檔案路徑
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = '檔案 "' + fn + '" 上傳成功'
else:
message = '檔案沒有上傳'
print ("""\
Content-Type: text/html\n
<html>
<head>
<meta charset="utf-8">
<title>碼農教程(codercto.com)</title>
</head>
<body>
<p>%s</p>
</body>
</html>
""" % (message,))
将以上代碼儲存到 save_file.py,并修改 save_file.py 權限:
chmod 755 save_file.py
以上 cookie 設定顔色 Gif 如下所示:
如果你使用的系統是Unix/Linux,你必須替換檔案分隔符,在window下隻需要使用open()語句即可:
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
檔案下載下傳對話框
我們先在目前目錄下建立 foo.txt 檔案,用于程式的下載下傳。
檔案下載下傳通過設定HTTP頭資訊來實作,功能代碼如下:
#!/usr/bin/python3
# HTTP 頭部
print ("Content-Disposition: attachment; filename=\"foo.txt\"")
print ()
# 打開檔案
fo = open("foo.txt", "rb")
str = fo.read();
print (str)
# 關閉檔案
fo.close()