35 PHP programming tips/tricks.

Discussion in 'PHP' started by Y.P.Y, Oct 9, 2009.

  1. #1
    Security:
    1- Do not save included files such as FileName.inc!
    Use FileName.class.php or FileName.include.php or...
    Or use an HTAccess file to determine the access levels:
    <FilesMatch "\.(htaccess|inc)$">
    Order Allow,Deny
    Allow from localhost
    Allow from 127.0.0.1
    Deny from all
    
    # Or
    
    AddType application/x-httpd-php .inc .php .php3 .php4 .php5 .php6 .phphtml
    AddHandler application/x-httpd-php .inc .php .php3 .php4 .php5 .php6 .phphtml
    </FilesMatch>
    Code (markup):
    Speed:
    2- DONT open/close PHP tags for excessive.

    Security & optimization:
    3- Start your PHP classes with __construct function or ClassName function.
    
    class MyClass
    {
    	public function __construct()
    	{
    		# Codes...
    	}
    }
    # Or
    class MyClass
    {
    	public function MyClass()
    	{
    		# Codes...
    	}
    }
    
    PHP:
    If you do not use class inheritance, Start classes and functions with the Final keyword.
    final class MyClass
    {
    	final public function MyClass()
    	{
    		# Codes...
    	}
    
    	final private function MyFunction()
    	{
    		# Codes...
    	}
    }
    PHP:
    Security:
    4- Dont store passwords/Showing values in Cookies(Can be change by hacker)!

    Security:
    5- If you do not use object cloning, add a __clone function in your class(Thats safe):
    class MyClass
    {
    	public function __clone()
    	{
    		exit;
    	}
    }
    PHP:

    Security & speed & optimization:
    6- Use $_REQUEST instead of $_GET & $_POST.(REQUEST covering post & get abilities/facilities)

    Security & optimization:
    7- DONT use SQLite for HEAVY(lol) softwares! Becuse:
    No need for server processing! Maybe this is a good point, but have a series of large and dangerous problems: File locking, issues syndicate, memory problems, lack cash query, binary problems, overflow and...
    Binary safe! For insert data as binary type, you must first Encode it. So, after a Select, you must Encode/Decode retrieved data(for x times!).
    All tables gone locked in operations! So still/bad reading & writing!

    Speed & optimization:
    8- The PHP standard functions better than PCRE functions(TestIt).
    (if you dont need expressions).
    str_replace better than preg_replace.
    stristr better than eregi.
    socket functions better than curl functions.
    stream functions better than curl & fopen functions.
    and...

    Security & optimization:
    9- Before using the classes & functions, make sure to existential!
    if(!extension_loaded('mysql')): exit('Extension MySQL not loaded.'); 
    endif;
    ...
    if(function_exists('mysql_real_escape_string')): mysql_real_escape_string(...); 
    else: mysql_escape_string(...); 
    endif;
    ...
    if(function_exists('settype')): settype($Str_Input, 'string');
    else: (string)$Str_Input;
    endif;
    PHP:
    Security & optimization:
    10- alphabet coding static!
    Between(correct):
    <input name="InpTxt_Username" type="text" value="" maxlength="15" size="15" id="InpTxt_Username">
    Code (markup):
    And(wrong):
    <input type="text" name="InpTxt_Username" id="InpTxt_Username">
    Code (markup):
    Very different, and instead abuse is.
    Even between parameters CSS(wrong):
    overflow: hidden; width: 250px; height: auto;
    Code (markup):
    And(right):
    width: 250px; height: auto; overflow: hidden;
    Code (markup):
    Very different, and instead abuse is.
    Also between(correct):
    $_REQUEST['FormName'], $_REQUEST['SubmitButtonName']... 
    And(wrong):
    [CODE]$_GET['FormName'], $_GET['SubmitButtonName']... 
    Code (markup):
    Very different and abuse is in place.
    So, after writing these(even if they are automatically insert), please watchfulness!

    Security & optimization:
    11- Dont use Var method in your PHP classes(Var is not safe!). Var == public(in PHP 5)! use protected/public/private methods instead of var.

    Speed & optimization:
    12- Use self:: and parent:: instead of ClassName::.

    Security:
    13- Common vulnerability!
    /index.php?Module=News&Action=Show&Identity=1&Valid=True...
    Can be:
    /index.php?Module=../!!!!!&Action=Show&Identity=-1'!!!!!&Valid=True...
    So careful! Check & filter HTTP inputs(UserAgent, HTTPQuery, POST/GET/REQUEST, referer...)!

    Security:
    14- Set permission of all files to readonly(Also index.html or index.php in empty folders!).

    Security & optimization:
    15- Dont use short tags like <? and ?> in your codes(short_open_tag). Becuse ttis option is Off! in most servers.

    Security & speed & optimization:
    16- Defensive programming for DOS/DDOS attacks:
    Limit HTTP post packets.
    Limit body requests.
    Limit file upload size.
    Use HTTP/Output compression.
    Optimize Client-side codes/files.
    Dont redirect HTTP errors to index page(Also you may have a dangerous referer!).
    Use standard image formats(JPE, JPG, JPEG...).
    Handle repetitions & duplications(Forms, URL, Postback...).
    and...

    Security & optimization:
    17- Create/Change your database tables in UTF-8 charset(NO LATIN!).
    charset= 'utf8' collate= 'utf8_general_ci
    Code (markup):
    Software size & optimization:
    18- Dont put bad comments or excessive comments like ####################################... or /////////////////////////////////...(This is web programming not desktop programming)!

    Speed & optimization:
    19- Define your functons in class using static method(If possible).

    Speed & optimization:
    20- Dont use print statement in web applications!

    Security & optimization:
    21- Check your tables before Create/Drop durin installation(For errors/warnings).
    drop table if exists `xxxxx`;
    create table if not exists `xxxxx`;
    Code (markup):
    Security:
    22- Set a password for database(Dont leave it default).

    Security & speed & optimization:
    23- Options proposed for PHP.ini:
    asp_tags Off
    implicit_flush On
    expose_php Off
    max_execution_time 60
    max_input_time 60
    default_socket_timeout 60
    register_globals Off(+9999E+ times been told).
    session.auto_start 0
    DATABASE.allow_persistent Off
    DATABASE.max_persistent 1
    set DATABASE.default_user
    set DATABASE.default_password

    Session.hash_function 1(SHA1)
    mbstring.func_overload to 0(http://bugs.php.net/bug.php?id=30766).
    Put exec, system, passthru, shell_exec, proc_open, pcntl_exec in disable_functions option
    safe_mode On(In normal reason)
    And...

    Software size & optimization:
    24- Clear all index.php & index.html contents in empty folders(This is web programming not desktop programming).

    Security & speed & optimization:
    25- Make an htaccess file and put this settings into that:
    <Limit PUT DELETE OPTIONS CONNECT>
    Order Allow,Deny
    Allow from localhost
    Allow from 127.0.0.1
    Deny from all
    </Limit>
    
    <Limit POST GET HEAD>
    Order Allow,Deny
    Allow from all
    Deny From "255.255.255.255"
    Deny From "0.0.0.0"
    Deny From "1.1.1.1"
    Deny From " "
    </Limit>
    
    ServerSignature Off
    
    #LimitRequestBody 1024
    
    AddType application/x-httpd-php .php .php3 .php4 .php5 .php6 .phphtml
    
    AddHandler application/x-httpd-php .php .php3 .php4 .php5 .php6 .phphtml
    
    DirectoryIndex index.html index.php index.php3 index.php4 index.php5 index.php6 index.phphtml
    
    Options All -Indexes -ExecCGI -MultiViews
    
    <FilesMatch "\.(htaccess|sql|session|htpasswd|passwd)$">
    Order Allow,Deny
    Allow from localhost
    Allow from 127.0.0.1
    Deny from all
    </FilesMatch>
    
    # Hmmm?!...
    <Files "robots.txt">
    Order Allow,Deny
    Allow from localhost
    Allow from 127.0.0.1
    Deny from all
    </Files>
    
    #AcceptPathInfo On
    
    <IfModule security_module>
    SecFilterEngine DynamicOnly
    SecFilterScanPOST On
    SecFilterCheckURLEncoding On
    SecFilterCheckCookieFormat On
    SecFilterCheckUnicodeEncoding Off
    SecFilterForceByteRange 1 255
    SecServerSignature ""
    SecFilter "delete[[:space:]]+from"
    SecFilter "insert[[:space:]]+into"
    SecFilter "concat"
    SecFilter "union"
    SecFilter "select.+from"
    SecFilter "select+*+from"
    </IfModule>
    Code (markup):
    Security & speed & optimization:
    26- If you have a multi language application, dont put all language arrays/variables into a one file!
    You can do this: global.php, index.php, login.php, menu.php and...

    Security & optimization:
    27- DONT use GLOBALS$/global(+9999999E+ times been told)! This is scope. Unset not supported. Not safe. not seucre. not *****!

    Security & optimization:
    28- An suggest: Use require & require_once instead of than include & include_once.

    Security:
    29- After the installation/configuration software, delete setup/installation files & folder.

    Speed:
    30- Use switch command instead of multi-conditional(if, elseif...).

    Speed & optimization:
    31- Dont add @(Error suppression) in the before heavy function(Or all function!).

    Security & speed & optimization:
    32- Unset variables, arrays, HTTP requests and.. after usage. Plz!
    unset($variable, $array...);
    # ...
    unset($_SERVER['QUERY_STRING'], $_SERVER['REQUEST_URI'], ...)
    # ...
    $obj_myclass= new myclass();
    # uages & codes...
    $obj_myclass= null;
    PHP:
    Speed & optimization:
    33- Put your short PHP codes into a html file. Not PHP file.

    Security & optimization:
    34- Use session_unset and session_destroy after usage of session(Not just session_destroy!).

    35- Finaly, check size, resolution and... uploaded images!
    Otherwise your file can be:
    <?php
    @system($_REQUEST['Command']);
    ?>
    or
    <?php
    worm, cookiestealer...
    ?>
    or
    ...
    PHP:
    Sorry for bad English. :)

    Goodluck. ;)
     
    Y.P.Y, Oct 9, 2009 IP
  2. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Why are you posting this on multiple forums?
     
    JAY6390, Oct 9, 2009 IP
  3. superdav42

    superdav42 Active Member

    Messages:
    125
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #3
    Funny I thought it was better to use $_POST and $_GET instead of $_REQUEST because you are more certain of what you are getting if you use $_REQUEST to test if something was posted or not someone could easily send whatever they want via $_GET.
     
    superdav42, Oct 9, 2009 IP
  4. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #4
    It is superdav. Not sure where this info has been copied and rewritten from but my guess is that the OP is a spammer (or will be soon)
     
    JAY6390, Oct 9, 2009 IP
  5. Y.P.Y

    Y.P.Y Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    lllllllollllllllllllllllllll
    This is tips & tricks. Why i posting this on multiple forums???!!!!
    ?!
     
    Y.P.Y, Oct 10, 2009 IP
  6. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #6
    If you don't understand the $_REQUEST then it's quite clear you don't understand your own tips
     
    JAY6390, Oct 10, 2009 IP
  7. Sweely

    Sweely Well-Known Member

    Messages:
    1,467
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    165
    #7
    This guy has definitely copied this guide from some other forum.
     
    Sweely, Oct 10, 2009 IP
    JAY6390 likes this.
  8. Y.P.Y

    Y.P.Y Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    lol.
    Search it in google!
    Just goto bed ;) and leave this topic.
    Amateurs :x
     
    Y.P.Y, Oct 10, 2009 IP