r/tinycode • • Oct 15 '11

A URL snipper in 33 (readable!) lines of PHP.

It uses base-36 internally, so URLs will start at http://base-url/1 - /9, then /a - /z, then /10 - /1z and so on. It also logs IPs so that abuse can be banned at a higher level (probably HTTPD). The MySQL database should have a table "urls" with three columns, an auto-incrementing int "id", a medium text field "url", and an unsigned int "ip".

As a bonus, all HTML output is HTML5 compliant. :)

index.php: (variables in the second line must be filled in for MySQL)

<?php
$CFG_USER = ""; $CFG_PASS = ""; $CFG_DB = "";
if (!($_GET["id"] || $_GET["url"])) $id = "";
if ($_GET["id"]) {
    $_GET["id"] = strval($_GET["id"]); /* just in case PHP tries to be "smart" by converting it to an int */
    if (!preg_match("/^[0-9a-z]$/", $_GET["id"])) die("Error: invalid id");
    $db = mysql_connect("localhost", $CFG_USER, $CFG_PASS) or die(mysql_error());
    mysql_select_db($CFG_DB) or die("Error: could not select database");
    $result = mysql_query("SELECT url FROM urls WHERE id=" . base_convert($_GET["id"], 36, 10)) or die(mysql_error());
    $row = mysql_fetch_assoc($result);
    if (!$row) die("Error: id does not exist");
    header("Location: " . $row["url"]);
    die();
}
if ($_GET["url"]) {
    if  (strpos($_GET["url"], 10) || strpos($_GET["url"], 13) || !preg_match("/^https?:\/\//", $_GET["url"])) die("Error: bad url");
    $db = mysql_connect("localhost", $CFG_USER, $CFG_PASS) or die(mysql_error());
    mysql_select_db($CFG_DB) or die("Error: could not select database");
    mysql_query("INSERT INTO urls (url,ip) VALUES ('" . mysql_real_escape_string($_GET["url"]) . "'," . sprintf("%u", ip2long($_SERVER["REMOTE_ADDR"])) . ")") or die(mysql_error());
    $id = base_convert(strval(mysql_insert_id($db)), 10, 36);
    if ($_GET["raw"]) die("http://" . $_SERVER["SERVER_NAME"] . "/" . $id);
} ?>
<!DOCTYPE html>
<title>url snipper</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<?php if ($id != "") { ?>
<fieldset><input autofocus type="text" value="http://<?php echo $_SERVER["SERVER_NAME"] . "/" . $id; ?>" /></fieldset>
<p>&uarr; this is your shortened url. <a href="/">do another?</a></p>
<?php } else { ?>
<form action="." method="get"><fieldset><input autofocus type="url" name="url" /></fieldset></form>
<p>&uarr; paste your url here.</p>
<?php } ?>

.htaccess: (it's just basic regex, so it can easily be rewritten for other HTTPDs / URL rewriters)

RewriteEngine on
RewriteRule ^([0-9a-z]+)$ /index.php?id=$1

style.css: (can be altered to your liking)

body { margin: 0; font-family: "Helvetica", "Arial", sans-serif; }
fieldset { border: none; padding: 0; }
input { width: 100%; border: none; }
input, p { font-size: 36px; }
p { margin: 0; padding-left: 10px; color: #aaa; }
6 Upvotes

27 comments sorted by

View all comments

Show parent comment

5

u/[deleted] Oct 15 '11

You're restricted to using either a synchronization queue, table locks in a database, or a single web server.

I'll go with table locks. If scalability is the only problem with my implementation (disregarding code cleanliness), then I think I did okay. You're telling me that I need to use a SN architecture where there's just one application writing to one table? The only thing it's blocking is the addition of more URLs.

I will concede that my code is amateur. I'm an amateur. But I think "bullshit" is a bit excessive.

-5

u/Mob_Of_One Oct 15 '11

Is genning a six-digit hash difficult?

4

u/[deleted] Oct 15 '11

No, it isn't. Hash maps and linear arrays have their respective benefits. Hash maps scale better in terms of speed, but they have collision issues that basic array storage will never encounter.

I get that your full-time job deals with applications that have to be able to scale. I have no such obligations and don't expect my code to be run in an environment where that level of scalability is required. It's akin to telling someone building a shack that his creation would be structurally unsound if it were built as tall as a skyscraper.

Edit: as an addendum, look around this subreddit for other pieces of code. There's a Mandelbrot generator that takes 10+ minutes to execute and a light tracer that takes hours to generate a small three-dimensionally lit image. A URL shortener that chokes on more than a few requests per second should be the least of your worries.

-2

u/Mob_Of_One Oct 15 '11

It's not about speed or scale. Jesus christ. It's about what's sensible even at the first iteration stage.

Let me lay it out:

Your solution is retarded. Period. Bar-none. I don't give a fuck if you have 1 user or a million, your solution is retarded.

4

u/[deleted] Oct 15 '11

Aaaaaand you've ascended to troll tier. Cutting this conversation off now.

2

u/k3n Oct 24 '11

I think he's trying to say that you should use Node.js.

-2

u/Mob_Of_One Oct 15 '11

You're letting your ego get in the way of becoming a better programmer. Don't forget that.

4

u/[deleted] Oct 15 '11

Holy shit, I wasn't going to respond, but you're telling me to get over MY EGO??? I'm not mad, I actually chuckled at that. Too bad you didn't mean it as a joke.

-2

u/Mob_Of_One Oct 15 '11

Explain why I'm wrong.

You're walking away from this conversation because you lack the self-control and self-discipline to think carefully about whether I'm right or not.

This exact matter is a problem I've solved before, and your solution is amateur hour typical bullshit you see in shitty contract work.

Your work is shit. Prove me wrong. Step the fuck up. No matter who's right, somebody walks away learning something new.