PHP / SQL data protection – anti SQL-Injection function

SQL Injection

SQL injection is a technique where malicious users can inject SQL commands into an SQL statement, via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web application.

SQL Injection Based on 1=1 is Always True
Look at the example above, one more time.
Let’s say that the original purpose of the code was to create an SQL statement to select a user with a given user id.
If there is nothing to prevent a user from entering “wrong” input, the user can enter some “smart” input like this:

UserId:

How to protect

PHP functions

The function

//Blind SQL-INJECTION Escape sequence. Line codes anti SQL-Injection
function anti_injection($input){
$clean=strip_tags(addslashes(trim($input)));
$clean=str_replace('"','\"',$clean);
$clean=str_replace(';','\;',$clean);
$clean=str_replace('--','\--',$clean);
$clean=str_replace('+','\+',$clean);
$clean=str_replace('(','\(',$clean);
$clean=str_replace(')','\)',$clean);
$clean=str_replace('=','\=',$clean);
$clean=str_replace('>','\>',$clean);
$clean=str_replace('<','\<',$clean);
return $clean;
}

How to use

$id=$_GET['id'];
$id_clean=anti_injection($id);
PHP / SQL data protection – anti SQL-Injection function

PHP directory listing in reverse order, function rsort

rsort

(PHP 4, PHP 5)

rsort — Sort an array in reverse order

Case history

PHP directory listing in reverse order

Description

bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array in reverse order (highest to lowest).

Parameters

array
The input array.

sort_flags
You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rsort() example

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Output

0 = orange
1 = lemon
2 = banana
3 = apple

 

PHP directory listing in reverse order, function rsort

PHP function calculate the distance between two coordinates (latitude, longitude)

function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lng1 *= $pi80;
$lat2 *= $pi80;
$lng2 *= $pi80;

$r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 – $lat1;
$dlng = $lng2 – $lng1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 – $a));
$km = $r * $c;

return ($miles ? ($km * 0.621371192) : $km);
}

PHP function calculate the distance between two coordinates (latitude, longitude)