aboutsummaryrefslogtreecommitdiffstats
path: root/redirect.cgi
blob: 9af5ed9161280cd4346eae0298457b8d98a06f3f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/perl -wT
# (c) 2019 Dennis Eriksen <https://dnns.no>

use strict;
use warnings;

use CGI;
use DBI;

my $q = CGI->new;       # create CGI object

# create database handler
my $dbh = DBI->connect("dbi:Pg:dbname=purl") or die $DBI::errstr;

# set the short
my $short = scalar $ENV{REQUEST_URI};
$short =~ s/^\///;

# SQL Query
my $query = qq(SELECT shorts.url FROM shorts WHERE shorts.short = ?;);

# run the query, and do an if on it
if (my $url = $dbh->selectrow_array($query, undef, $short)) {
    $query = qq(UPDATE shorts SET count = count + 1, last_visited = now() WHERE short = ?;);
    my $sth = $dbh->prepare( $query );
    my $rv = $sth->execute( $short ) or die $sth->errstr;
    print $q->redirect($url);
}
else {
    print $q->header(-status=>'404 Not found',-charset=>'utf-8');
    print <<notfound
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
notfound
}

# disconnect from database
$dbh->disconnect();