Showing posts with label cgi. Show all posts
Showing posts with label cgi. Show all posts

Sunday, July 24, 2011

getting variables from GET method in perl (cgi)

Suppose we have a page with the following form:

<form action="index.pl" method="get">
<input type="text" name="search_for" size="30" />
<input type="submit" value="search" />
</form>

So, there's a text input field named "search_for", and a submit button.
The following code gets the variables set in QUERY_STRING (whatever is after pagename.pl?...), into the $arg associative array. So we can get the value of "search_for" by $arg{"search_for"}.

for (split /\&/, $ENV{QUERY_STRING}) {
($key,$val) = split /\=/;
$val =~ s/\+/ /g;
$val =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/ge;
$arg{$key} = $val;
}
print "data searched for is =
$arg{search_for}
";

Friday, July 22, 2011

apache cgi enabled site on specific dir

As an example, using /home/username/some_test_dir/, although it's obviously better not to use home dirs for this kind of things.

These settings allow you to access the files in /home/username/some_test_dir on the web by localhost/some_web_dir (set in alias).
And also enables you to run cgi scripts there.
In the shell:
a2enmod cgi #enable cgi
a2ensite site-filename
/etc/init.d/apache2 reload #in debian

Where filename, is the name of a file containing the following text, placed in /etc/apache2/sites-available/:
<VirtualHost *:80>
 ServerAdmin this_is_my_name@my_test_domain.com

 DocumentRoot /home/username/some_test_dir/
 <Directory "/home/username/some_test_dir">
  AllowOverride None
  Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
         allow from all
                AddHandler cgi-script .cgi .pl .sh
 </Directory>
        Alias /some_web_dir "/home/username/some_test_dir/"

 ErrorLog ${APACHE_LOG_DIR}/some_web_dir_error.log

 # Possible values include: debug, info, notice, warn, error, crit,
 # alert, emerg.
 LogLevel warn

 CustomLog ${APACHE_LOG_DIR}/some_web_dir_access.log combined
</VirtualHost>

simple cgi shell script

You just print out an html page. The only other thing you have to care about is outputting:
Content-type: text/html

(followed by two newlines characters)
And then, as long as your apache settings are working and the file has executable permission (chmod a+x filename), your browser should display the proper page.

#!/bin/sh
#you need this part for cgi handling
printf "Content-type: text/html\n\n"

# contents
echo "<html>"
echo "<head><title>Dude</title></head>"
echo "<body>"
echo "<h1>some header</h1>"
echo "awesome"
echo "</body>"
echo "</html>"