Jump to content


Photo
- - - - -

35 PHP programming tips/tricks.


  • Please log in to reply
1 reply to this topic

#1 Yousha(Y.P.Y)

Yousha(Y.P.Y)

    Young Padawan

  • Members
  • Pip
  • 1 posts
  • Gender:Male
  • Location:Tehran - Iran

Posted 10 October 2009 - 09:18 AM

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

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

#2 rc69

rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 10 October 2009 - 12:21 PM

I have several issues with this article, below are what i whould suggest to fix some of the issues with it. For additional tips on php optimization, i would recommend 10 Advanced PHP Tips Revisited by Smashing Magazine.

---------

2. Myth. Excessive open/closing php tags are just hard to read, there is no conclusive evidence that they actually affect speed.

3. Adding empty constructors is good programming practice, but does not affect security. Also, you should not abuse the final keyword like that. For one, it is not available in PHP 4, so if you intend to keep backwards-compatibility, things will break. Additionally, if you are not using inheritance then it is does nothing.
ref: http://php.net/manua....oop5.decon.php

6. NO! Very bad suggestion. PHP.net says why better than I can:

The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted.

ref: http://php.net/manua...les.request.php

9. Unless you are uber-paranoid about backwards-compatibility and cross-platform compatibility, then this is a waste of time. The only time you would want to do a check like this would be at the start of your program to determine which functions you should use (but again, only if you are worried about cross-platform compatibility). If you are developing for yourself (i.e. you know the server/specs you'll be working with), then there is absolutely no reason to do this.

10. I have no idea what is being suggested here. It looks to me like you are saying the order in which you write out HTML attributes and CSS properties matters. This is not true. The only thing that matters in that respect is that you are consistent (i.e. define an order for yourself and stick to it, don't randomly change from one tag/selector to another). And again, don't use $_REQUEST.

11. Again, not entirely true. If you are worried about working in PHP 4, you have to use 'var'. If you know that you will be working only with PHP 5, then use the public/private/protected keywords as appropriate.
ref: http://php.net/manua....visibility.php

12. That depends on the context in which you are writing. If you are not inside a class (or you need to reference a different class), then you have to use ClassName::
ref: http://php.net/manua...nekudotayim.php

13. This needs to be made more generic. The general rule of thumb is: Never trust user input (i.e. always sanitize your data).

15. The issue with short-tags is only relevant if you are concerned about cross-platform compatibility. If you are developing for yourself (i.e. you have control over the settings on the server), then feel free to use short open tags.
ref: http://php.net/manual/en/ini.core.php

18. Excessive comments to add to the about of diskspace your files use, they do not affect the runtime at all. When writing code, it is important that you add as many comments as necessary to understand what is going on (so if somebody else were to look at it, or you 6 months later, then they would know what is happening).

19. I don't know what the reasoning behind making all functions in a class static (if possible) would be. Making everything static removes the ability to instantiate several instances of the same object without causing overlap. If you are going to define something as static, make sure you know why you are making it static.
ref: http://php.net/manua...oop5.static.php

20. By saying that you shouldn't use the print() statement in web applications, I'm assuming you are implying we should use echo() instead? That is also a bit of a myth; I refer you to the php.net recommended article of echo vs print: http://www.faqts.com...ml/aid/1/fid/40
ref: http://php.net/manua...nction.echo.php

24. Irrelevant. The index file you choose to put inside empty files can and probably should have some contents. Specifically, it should likely tell the user they are doing something wrong, or redirect them back to where they should be.

25. You need to be careful when messing with security settings in the .htaccess file. For one, some options are disabled and can result in HTTP 500 errors being generated, but more importantly: If you are on a shared server, it should be configured by default to be at the highest reasonable level of security (that's not to say you should assume such is the case).

27. Are you saying that it is bad to use the $GLOBALS superglobal, or that it is bad to use global variables? I will agree on one point, you need to be cautious when using globals (very cautious), but they are not all bad. In the right context, they are very useful. Other than that, accessing the $GLOBALS array inside a function is faster than using the global keyword (according to personally performed tests).
ref: http://php.net/manua...es.scope.global

31. Using the '@' error control operator is bad for production code. In production, you should (technically) turn error_reporting() off and handle all errors yourself. However, that is not always practical.
ref: http://php.net/manua...rrorcontrol.php

32. While it is true that you should manage your variables (i.e. unset() them when they are no longer in use), purging something like the $_SERVER array is border-line excessive (and in fact should not be recommended).

33. What? PHP code in an .html file? No, PHP belongs in .php files. Putting them in anything else will create security holes in your application (.html files are not parsed for PHP, so people can gain access to your source).

Edited by rc69, 10 October 2009 - 12:21 PM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users