Script

Filter
2004-11-30

Säkerhet i php

Php
Grundläggande regler vid kodning
1. Register_global off
2. Never trust user data
3. AddType application/x-httpd-php .htm (httpd.conf) changes .php to .htm 
4. Put key files outside your document root (dbconnect.inc.php)
5. Name inc-files x.inc.php instead of x.inc 
6. Hide serverinfo: "ServerSignature Off" and "ServerTokens Prod" (httpd.conf)
7. Hide php "expose_php Off" (php5.ini)
8. Hide errors "display_errors Off" "log_errors On" (php5.ini)
9. Restrict general database access (root and iuser @localhost in mysql)
10. Use include_once()
11. Pre-initialise important variables to safe values
12. Be wary of session fixation (can be hijacked):
  <A HREF="http://www.yoursite.com?PHPSESSID=abc123">Click here!</A>
  Change session IDs on privilege elevation:
  a) Validate (ie against a database) and if user is OK then
  b) session_regenerate_id()
13. Use Safe mode (php5.ini)
  a) safe_mode_include_dir: In safe mode the UID of the owner of the script normally must match the UID of the owner of the file being read. But not in this dir
  b) safe_mode_exec_dir: The only dir where exec() works
  c) safe_mode_allowed_env_vars: list of environment variables that the user can change
  d) open_basedir: Limit the location from where files can be read (tricky prefix syntax,  /home/paul matches both /home/paul_hax and /home/paul_hex, write /home/paul/ instead). Works regardless of whether safe mode is enabled
  e) disable_functions: Stops list of functions, for example: readfile, exec, fopen
  f) disable_classes: list of classes to block
2004-11-25

@ Operator

Php
Undvik felmeddelanden
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP,
any error messages that might be generated by that expression will be ignored.
2004-11-25

Ta emot formulär

Php
Ett otroligt smart sätt att ta emot formulärdata
<? foreach ($_POST as $nyckel => $varde) {
    if (is_array($varde)) {
        $varde = implode(', ', $varde);
    }
    if (get_magic_quotes_gpc() ) {
        $nyckel = stripslashes($nyckel);
        $varde  = stripslashes($varde);
    }
    //echo "$nyckel = $varde<br>";
    $$nyckel = $varde; // Obs $$!
} ?> 
2004-11-25

Hämta data från mysql

Php
Ett smartare sätt att hämta data från databas (lagras här i en fil med output buffering)
<? 
ob_start();
$result = mysql_query("select * from table");
while ($row = mysql_fetch_assoc($result)) {
    extract($row);
    print "Some info A: $SomeInfoA\n";
    print "Some info B: $SomeInfoB\n";
    print "Some info C: $SomeInfoC\n";
}
$output = ob_get_contents();
ob_end_clean();
file_put_contents("employee.txt", $output);
?> 
2004-11-22

Defaultvärden för superglobals

Php
Se till att globala variabler har ett defaultvärde (om det så bara är 0 eller '')
if(!isset($_GET['size'])) $_GET['size'] = 44;
if(!isset($_POST['text'])) $_POST['text'] = 'Hello';
🙂