# CGI mittels Shell Programmierung: Auf die harte Tour :)



## RedWing (4. Februar 2007)

Hallo,

als erstes in apache2.conf bzw httpd.conf folgendes hinzufügen:


```
AddHandler cgi-script .sh
    <Directory "/home/*/public_html/cgi-bin">
        Options ExecCGI
        SetHandler cgi-script
    </Directory>
```

Danach unsre html Form:


```
<html>
<head> <title> Test form </title> </head>
<body>
    <form method="post" action="./cgi-bin/cgi_example.sh">
        <pre>
Name:    <input type="text" name="name" />
Vorname: <input type="text" name="given_name" />
    <input type="submit" value="Send" />
        </pre>
    </form>
</body>
</html>
```

und jetzt noch unser Shell CGI Skript abgelegt in ~/public_html/cgi-bin :
cgi_example.sh:



```
#! /bin/bash

function init() {
    #if request method is post read out the parameters from stdin, 
    #otherwise from ${QUERY_STRING}
    if [ ${REQUEST_METHOD} = "POST" ]; then
        read parameter_data
    else
        parameter_data=${QUERY_STRING}
    fi
    echo ${parameter_data}
}

function get_param() {
    value=$(echo ${2} |
            awk -F '[&=]' \
            '{ \
                for (i=1; i <= NF; i++) { \
                    if ($i == "'${1}'") \
                        print $(i+1) \
                } \
            }')
    echo ${value}
}

echo "Content-Type: text/html; charset=ISO-8859-1"
echo ""
echo "Request method: ${REQUEST_METHOD}<br />"

#extract parameters
parameter_data=$(init)
name=$(get_param "name" ${parameter_data})
given_name=$(get_param "given_name" ${parameter_data})

#print parameters
echo "Given name: ${given_name} <br />"
echo "Name: ${name}"
```

Nach Ausfüllen und Absenden der Inputform in unsrem Browser sollte das Skript anfangen zu rattern und folgende Ausgabe im Browser bringen:

```
Request method: POST
Given name: YourGivenName
Name: YourName
```

Gruß,
RedWing


----------

