使用者工具

網站工具


program:shellscript:cgi_example

設定 Content-Type

記得, 一定要空一行

echo "Content-Type: text/html; charset=utf-8"
echo ""

Query String

直接使用 ${QUERY_STRING}即可取得 url? 後的字串

環境變數

直接 call linux env 可取得所有的環境變數

echo "Content-Type: text/html; charset=utf-8"
echo ""
/usr/bin/env

HTML 頁面上的結果:

GATEWAY_INTERFACE=CGI/1.1
REMOTE_ADDR=192.168.100.25
QUERY_STRING=/Music%2F2013-05-19%20%E6%B1%9F%E8%95%99%20-%20%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B%2F01.%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B.mp3&1379934788862
REMOTE_PORT=1970
DOCUMENT_ROOT=/etc_ro/www
HTTP_USER_AGENT=Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0
SERVER_SIGNATURE=
HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
SCRIPT_FILENAME=/etc_ro/www/cgi-bin/get/getFile.cgi
HTTP_HOST=192.168.100.208
REQUEST_URI=/cgi-bin/get/getFile.cgi?/Music%2F2013-05-19%20%E6%B1%9F%E8%95%99%20-%20%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B%2F01.%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B.mp3&1379934788862
SERVER_SOFTWARE=Apache/2.2.13 (Unix)
HTTP_CONNECTION=keep-alive
PATH=/sbin:/usr/sbin:/bin:/usr/bin
HTTP_ACCEPT_LANGUAGE=zh-tw,zh;q=0.8,en-us;q=0.5,en;q=0.3
HTTP_REFERER=http://192.168.100.208/explorer/explorer.htm
SERVER_PROTOCOL=HTTP/1.1
HTTP_ACCEPT_ENCODING=gzip, deflate
REQUEST_METHOD=GET
SERVER_ADMIN=you@example.com
SERVER_ADDR=192.168.100.208
PWD=/media/sdc1/WebUI2/cgi-bin/get
SERVER_PORT=80
SCRIPT_NAME=/cgi-bin/get/getFile.cgi
SERVER_NAME=192.168.100.208

上面的變數均可直接使用,如:

echo "Content-Type: text/html; charset=utf-8"
echo ""
echo "<br>QUERY_STRING=${QUERY_STRING}<br>"
echo "<br>REQUEST_URI=${REQUEST_URI}<br>"
echo "<br>HTTP_USER_AGENT=${HTTP_USER_AGENT}<br>"
echo "<br>REMOTE_ADDR=${REMOTE_ADDR}<br>"
...

HTML 頁面上的結果:

QUERY_STRING=/Music%2F2013-05-19%20%E6%B1%9F%E8%95%99%20-%20%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B%2F01.%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B.mp3&1379934788862
 
REQUEST_URI=/cgi-bin/get/getFile.cgi?/Music%2F2013-05-19%20%E6%B1%9F%E8%95%99%20-%20%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B%2F01.%E9%81%A0%E8%B5%B0%E9%AB%98%E9%A3%9B.mp3&1379934788862
 
HTTP_USER_AGENT=Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0
 
REMOTE_ADDR=192.168.100.25

URL Decode

將 %20… 轉為 \x20…

# decodeURI
echo "url: ${QUERY_STRING}<br>"
echo "decode-1: $(echo ${QUERY_STRING} | sed 's/\\/\\\\/g;s/\(%\)\([0-9a-fA-F][0-9a-fA-F]\)/\\x\2/g')<br>"
echo "decode-2: $(echo ${QUERY_STRING} | sed 'y/+/ /; s/%/\\x/g')<br>"

echo 加上 -e 才會把 \x20… 顯示為 ' '… (UTF-8編碼)

完整的code

filepath=`echo ${QUERY_STRING} | cut -d'&' -f1`
# decodeURI
filepath="$(echo ${filepath} | sed 'y/+/ /; s/%/\\x/g')"
# 將結果重新指定給 filepath (加 -e 為把 \x20... 顯示為 ' '...)
filepath=$(echo -e "${filepath}")
program/shellscript/cgi_example.txt · 上一次變更: 2013/09/23 11:40 (外部編輯)