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);

Hide email headers in Postfix

Write this code in /etc/postfix/header_checks

/^Received:/                    IGNORE
/^X-PHP-Originating-Script:/    IGNORE
/^X-Originating-IP:/            IGNORE
/^X-Mailer:/                    IGNORE
/^Mime-Version:/                IGNORE

Apache – mod_rewrite rules

Examples to configure rewrite rules in .htaccess file:

http://example.com/page.php

RewriteEngine On
RewriteRule ^demo/?$ /page.php [L,NC]


Rewrite localization url with $_GET[‘lang’] variable
http://example.com/english

RewriteEngine On
RewriteRule ^(.*)/$ /$1 [R=permanent]
RewriteRule ^([a-z]{2})$ /index.php?lang=$1


Redirect 301
http://www.example.com/ to http://example.com/

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Detect Browser Language in PHP

<?php   
    $lang = getenv("HTTP_ACCEPT_LANGUAGE");
    $set_lang = explode(',', $lang);
    if (isset($_POST['lang'])) 
        {
            $taal = $_POST['lang'];
            setcookie("lang", $taal);
            header('Location: /p/');
        }
    else 
        {
            setcookie("lang", $set_lang[0]);
            echo $set_lang[0];
            echo '<br>';
            echo $set_lang[1];
            header('Location: /p/');
        } 
?>

Nivo slider options

$("#nivoSlider").nivoSlider({
effect: 'random', // Specify sets like: 'fold,fade,sliceDown'
slices: 15, // For slice animations
boxCols: 8, // For box animations
boxRows: 4, // For box animations
animSpeed: 500, // Slide transition speed
pauseTime: 3000, // How long each slide will show
startSlide: 0, // Set starting Slide (0 index)
directionNav: true, // Next & Prev navigation
controlNav: true, // 1,2,3... navigation
controlNavThumbs: false, // Use thumbnails for Control Nav
pauseOnHover: true, // Stop animation while hovering
manualAdvance: false, // Force manual transitions
prevText: 'Prev', // Prev directionNav text
nextText: 'Next', // Next directionNav text
randomStart: false, // Start on a random slide
beforeChange: function(){}, // Triggers before a slide transition
afterChange: function(){}, // Triggers after a slide transition
slideshowEnd: function(){}, // Triggers after all slides have been shown
lastSlide: function(){}, // Triggers when last slide is shown
afterLoad: function(){} // Triggers when slider has loaded
});

PDO connection with MySQL

<?PHP
# gestione delle eccezioni in fase di connessione con PDO

// collegamento al database
$col = 'mysql:host=localhost;dbname=DATABASE_NAME';

// blocco try per il lancio dell'istruzione
try {
  // connessione tramite creazione di un oggetto PDO
  $db = new PDO($col , 'username', 'password');
}
// blocco catch per la gestione delle eccezioni
catch(PDOException $e) {
  // notifica in caso di errorre
  echo 'Attenzione: '.$e->getMessage();
}


/* disabilitazione dell'auto-commit
$db->beginTransaction();

// esecuzione delle query
$sql = $db->exec("UPDATE filnet_page SET img_code = 'AU002.jpgTEST' WHERE id = 67");

// applicazione delle modifiche
$db->commit(); */


# utilizzo del metodo query()

// definizione della query 
$sql = 'SELECT field1, field2 FROM table_name ORDER BY id';  

// visualizzazione dei risultati
foreach($db->query($sql) as $row){  ?>

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