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>

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...
	}
}

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...
}
}

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

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;

Security & optimization:
10- alphabet coding static!
Between(correct):

<input name="InpTxt_Username" type="text" value="" maxlength="15" size="15" id="InpTxt_Username">

And(wrong):

<input type="text" name="InpTxt_Username" id="InpTxt_Username">

Very different, and instead abuse is.
Even between parameters CSS(wrong):

overflow: hidden; width: 250px; height: auto;

And(right):

width: 250px; height: auto; overflow: hidden;

Very different, and instead abuse is.
Also between(correct):

$_REQUEST['FormName'], $_REQUEST['SubmitButtonName']... 
And(wrong):
[CODE]$_GET['FormName'], $_GET['SubmitButtonName']... 

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

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

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/B.
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>

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;

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
...

Sorry for bad English. 🙂

Goodluck. 😉

    36 - be negative in your coding and cover both conditions, for example:

    if(acceptable condition){
       //do something positive..
    }
    

    That's dangerous. If there is not an acceptable condition, we have not dealt with it and the coding in the braces will not occur. Better to do the following:

    if(acceptable condition){
       //do something positive..
    }else{
      //handle the negative .. do we need to email someone? optimize something? store the lack of that condition to make analysis later on?  This is where your coding can really shine and function on a high level
    }
    

    Of course in error checking you are usually construing in the negative

    if(!valid email){
       //error, alert user, exit, etc.
    }
    

      37 -
      if you use an array in a config page like $settings and only declare it like this:

      $settings['normalRecordView']=25;
      $settings['showActiveColumns']=true;
      

      you can "secure it by first unsetting it:

      unset($settings); //this prevents any passage of array keys in query - the array is now "yours" !!
      $settings['normalRecordView']=25;
      $settings['showActiveColumns']=true;
      

        there are several of theses i disagree with, some seem to be just personal preferences, others i believe would do the opposite of what the op says (making things slower not faster)

        6 comes to mind, as it can be populated in 4 ways, depending on your php set up, not knowing exactly the source of a var seems particularly dangerous.

          Some of what you list under security and optimisation are about good design rather than security or optimisation. For example, declaring member variables private unless there is special reason to do otherwise.

          Using $REQUEST instead of $GET or $_POST is arguably a reduction in security, though only marginally.

            Y.P.Y wrote:

            laserlight, can you delete this thread?

            Yes, but why do you want them deleted?

              Write a Reply...