Tuesday, April 07, 2009

Speed v. Safety

When programming, you have to walk a fine line between getting code out, and making code secure.

I'm actually not talking about general security issues, although there are unfortunate circumstances when you (as an employee) don't have the option of taking the time to make your code (or your predecessor's code) secure.

I'm talking about coding for things that should "never happen." I'm talking about coding for that particular sequence of actions you think no one will ever do, or that edge case that no one will ever hit, or even that thing you think can never happen.

I try to be reasonable with what I do, although I like to err on the side of caution. For example, here's a bit of PHP code:

<?php
header("Location: index.php");
?>

Theoretically, that is supposed to redirect the visitor to the index.php page...say, if they weren't authorized to be on the current page. I always assumed it always worked, no exceptions.

However, back in the mists of my early programming, some person, or webpage, or something suggested putting an "exit" statement afterwards, just in case it didn't. That way, if the person wasn't redirected to the proper page, the current page would just die. It's better than having an unauthorized person viewing the page.

<?php
header("Location: index.php");
exit;
?>


So I've always done that. Better safe than sorry. I found out the reason for doing so today: apparently, it's up to the web browser (or web crawler, etc.) whether or not it wants to obey the headers, including the "Location" one in the PHP code above. I knew that, I just never really made the connection between that fact and this situation. So, if a browser or crawler doesn't obey the header, the page will just die.

You learn something new each day. I'm glad I was already writing secure code (for that situation), even if I didn't know why...

No comments: