PHP: Main
First of all, welcome to this tutorial!
You are expected to have a basic knowledge about using MySQL with PHP (and ofcourse PHP itself).
This tutorial will go over some basic security issues that most beginners seem to forget.
Part 1: Preventing SQL injects
1.1 The URL
SQL Injects: a PHP programmer's biggest fear. Say, you have a neat flash portal built and you use shiny links like
this: portalview.php?flash=55325. This works very well, ofcourse. Untill you have a visitor that thinks:
"hey, let's screw up this stupid kid's DB (with an evil grin)". Without the needed security, he could just do this:
portalview.php?id=55; DROP TABLE flash
And I guess you realise what that does. Indeed. It drops your valued flash table! All data is lost and you sit
there... hoping you have a backup.
Ofcourse, there is some easy way to prevent this =) This magical function is called Intval(). It basically takes the first integer value
from a string.
So our example page portalview.php should contain this code:
<?php
$id = intval($_GET['id']);
?>
Problem solved, and only the numerical value 55 is passed in the previous example, and not that dreaded SQL inject
;)
1.2 The Form
Well, basically, the same thing can be done from within a form. BUT ofcourse there is a way around this again =)
The used function is either mysql_real_escape_string() or addslashes(). These basically do the same, although
the first function is better =)
What they do is this: they put an escape character, in this case a backslash (\), before every character that could
be used to cause an SQL inject. Mostly, this is a quote (').
So, easyness says it:
<?php
$name = mysql_real_escape_string($_POST['name']);
?>
Note: Most webservers will have magic_quotes_gpc() on. This automatically adds these slashes. but don't rely
on it!
Part 2: register_globals
This was THE biggest mistake PHP ever made. It's a PHP ini setting that automatically registers your global
variables ($_GET, ...) to normal variables ($id, $name, ...). It's known to be horribly insecure and with it not
being enabled everywhere, many people usually whine about their scripts not working.
Nobody ever explained to me why exactly it's so insecure, but I can think of a few things...
Take this script for an example:
<?php
$funcs = array("lower", "upper");
for($i = 0; $i < 12; $i++)
{
$func = "strto".$funcs[array_rand($funcs)];
@$pass .= $func(chr(mt_rand(48, 93)));
}
?>
It's a script I wrote for generating passwords. BUT with register_globals on, I could access this page like this:
passgen.php?pass=yay. this would prefix the generated password with "yay".
In this example, it isn't a security risk per se, but it can be riskier on other occasions ;)
I guess this kinda sums up this small tutorial =) I hope it was helpful, and feel free to leave any notes!
-- Bekko