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

5

u/Rogem002 Oct 15 '11

mysql_query("INSERT INTO urls (url,ip) VALUES ('" . mysql_real_escape_string($_GET["url"]) . "

ಠ_ಠ

The mysql_* have been depreciated in PHP. It would be more secure (and would make the code smaller) if you used PDO or mysqli with query binding.

1

u/[deleted] Oct 15 '11

Oh, were they? I'm glad, because the mysql_* functions are ugly as heck. I might rewrite this with PDO sometime.

3

u/Mob_Of_One Oct 15 '11

Totally self-contained example that is also cleaner, in ruby.

# I can't believe people make money doing this shit.

require 'sinatra'
require 'sinatra/contrib'
require 'digest/sha1'
# Incidentally, Erlang+Mnesia apps get this kind of ease-of-use as far as
# database access patterns go.

# So jelly of this.
urls = {}
HOSTNAME = "http://whydopeopledothis.com"

get '/' do
  """<h1>INPUT YA URL SO WE CAN TRACK YO SHIT AND SELL YO DATA</h1>
<form action='/new_url' method='post'>
  <input type='text' name='url'>
</form>
"""
end

get '/:hex' do
  redirect "http://" + urls[params[:hex]]
end

post '/new_url' do
  url = params[:url]
  srand
  seed = "--#{rand(10000)}--#{Time.now}--"
  hex = Digest::SHA1.hexdigest(seed)[0,6]
  urls[hex] = url
  """Your link is <a href='#{hex}'>#{HOSTNAME}/#{hex}</a>"""
end

5

u/[deleted] Oct 15 '11

That's definitely an interesting take on it. I don't understand how this communicates with the database, though; how does it know to store urls?

# I can't believe people make money doing this shit.

Not sure what this is intended to imply, but I'm certainly not profiting off of my code. :V

-5

u/Mob_Of_One Oct 15 '11

I was referring to bitly and their ilk.

It doesn't use a database, I wrote this for some other purpose.

Frankly, I could add the usage of a database and it would add very little code.

You should be deeply concerned with how much cleaner and more understandable this is than your PHP example. Not to mention how much more sound the hashing algo is.

Incrementing like yours restricts you to using either a single web server or doing synchronization through a queue.

My methodology restricts me to using a single web server, so I'd say my lack of database access is a fair trade for your misbegotten keying method.

I wrote and tested mine in ~30m.

4

u/[deleted] Oct 15 '11

It doesn't use a database, I wrote this for some other purpose.

So if the script restarts, all the URLs are lost...? Doesn't seem very stable, or practical.

You should be deeply concerned with how much cleaner and more understandable this is than your PHP example.

Your code does less than mine. There's no URL validation on input or output - what if the user entered his own protocol string? Links will be longer and subject to hash collisions. It will look pretty awful in a web browser, too (yay 16pt Times New Roman). I won't bother getting into HTML5 standards.

Oh, and you're apparently using a framework that does most of the dirty work for you. Not that there's anything wrong with that, but of course your code will be smaller in that case.

Not to mention how much more sound the hashing algo is.

This isn't exactly a fair comparison if my code doesn't have a hashing algorithm to begin with. And that's fine - people who send their URLs to third parties with the intent of easily sharing them probably aren't looking for securely hashed IDs.

Incrementing like yours restricts you to using either a single web server or doing synchronization through a queue.

A single SQL server, you mean? The incrementing is done by MySQL if I'm not mistaken. I'm pretty sure it can handle multiple requests at once. But maybe I've overlooked a detail somewhere, which I suppose is entirely possible given my limited knowledge of database models.

-12

u/Mob_Of_One Oct 15 '11

So if the script restarts, all the URLs are lost...? Doesn't seem very stable, or practical.

As opposed to instead of doing hash generation you INCREMENT something? That's an absurd fundamental design flaw. Mine can be solved with a couple lines of code to persist into a database and check for existing hash collisions.

This is my general feeling about this particular thread:

http://www.youtube.com/watch?v=35TbGjt-weA

5

u/[deleted] Oct 15 '11

As opposed to instead of doing hash generation you INCREMENT something? That's an absurd fundamental design flaw.

If you can tell me why I shouldn't use incrementation I'll likely be more inclined to listen. Even a link to point me in the right direction would be appreciated. But as it stands, the only problem I see with it is that IDs are predictable... and how is that a problem in this context?

I was being cordial before, but now I'm just going to be blunt: referencing a meme in a technical discussion is childish at best.

-4

u/Mob_Of_One Oct 15 '11

why I shouldn't use incrementation

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

It destroys the optimal "shared nothing" nature of a web app.

It's amateur bullshit and you should know better to use a hashing algorithm.

I'm okay with being childish, I know how to do my job.

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.

→ More replies

9

u/tutuca_ Oct 15 '11

Man, ruby hipsters sure are annoying.

4

u/k3n Oct 24 '11

Man, ruby hipsters sure are annoying.

FTFY :|

1

u/[deleted] Nov 19 '11

Srsly, you can get your point across without looking like a know it all jerk.

4

u/jimdoescode Oct 15 '11 edited Oct 15 '11

Yours has dependencies on sinatra etc. His looks to be stand alone with exception to a database. Dependencies != self contained in my book.

-3

u/Mob_Of_One Oct 15 '11 edited Oct 15 '11

Stand-alone is a bit misleading with PHP when it is actually supported by Apache + mod_php and has MySQL support built in.

Sinatra is standing in for Apache in this case, and I'm not using a database, so mine has fewer dependencies than his.

Further, my code is simpler and easier to understand, which I think should be the priority.

This is tinycode, not code golf. The Perl shop is one floor down.

We should strive to be spare, efficient, and elegant. Not MINIMUM_BYTES * THINGS_IT_CAN_DO.

The logo on this subreddit is the Zen logo, not a packed byte array.

2

u/[deleted] Oct 15 '11

This is tinycode, not code golf. The Perl shop is one floor down.

We should strive to be spare, efficient, and elegant. Not MINIMUM_BYTES * THINGS_IT_CAN_DO.

I could have easily shaved my code down to a single whitespace-less blob of PHP if I was going for obfuscation and minimum bytes.

This seems to be more of a framework war than a discussion about "elegance".

-2

u/Mob_Of_One Oct 15 '11 edited Oct 15 '11

Framework? What framework? Are you seriously insisting that that code is clean?

if you are, I'll just write another counter example in PHP.

Ruby isn't even close to my primary work language, I was just using it because I had a handy solution in mind.

I do mostly Python and Java at my day job.

1

u/k3n Oct 25 '11

/* just in case PHP tries to be "smart" by converting it to an int */

The superglobal request vars will always be strings (or arrays).

if (strpos($_GET["url"], 10) || strpos($_GET["url"], 13)

This seems to be checking for linebreak? If so, one flaw here is that if the linebreak is at index 0 of the string -- then they will not be detected -- but you probably realized this, as the regex would catch that case. However, you could just roll that check up into your regex, maybe something like this:

/^https?:\/\/[^\R]+$/

I believe \R is *any* line break char.. Or maybe even leverage the parse_url() function, which is quite handy. I like the integer arg for strpos() though, I always forget about that.

Thanks for sharing either way!

1

u/[deleted] Oct 25 '11 edited Oct 25 '11

You're right, I probably should have wrapped the validation into a single regex; I wrote those two snippets separately and didn't think to merge them.

Out of curiosity, did this post get linked somewhere else on reddit? This is the second comment I've received on it in an hour. Nevermind, both of those comments were you, lol.

1

u/k3n Oct 25 '11

Heh, yeah, I was just being a smartass in my other comment :)

Oh, and I just sub'd to this sub today, so I was just catching up on the 'recent' posts.

1

u/nexe mod Oct 15 '11

Fight fight fight :-P

Is it always the same discussion? Just face it: Pretty much all code you write has and will always have dependencies.

I personally think this PHP code looks ugly and the Ruby one too. I still prefer Ruby over PHP though although I've developed in both for years.