PDA

View Full Version : آموزش: 35 نکته اموزشی php نیاز به ترجمه



javadth
پنج شنبه 22 تیر 1391, 13:55 عصر
امروز هم با 35 نکته اموزشی php امد
ولی نیاز به ترجمه داره و ضمنا خود این هم از یه زبان دیگه به english ترجمه شده

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.


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

javadth
شنبه 24 تیر 1391, 20:40 عصر
کسی نمیخواد ترجمه کنه ؟/

mtchabok
چهارشنبه 28 تیر 1391, 12:57 عصر
دقیقا ترجمه نیست ولی مهفوم رو فک کنم رسوندم ...

1- سعی کنید تا از پسوند .php برای فایلهای اسکریپتتون استفاده کنین زیراکه در برخی از وب سرورها این فایل است که پردازش میشود . اگر مایل به اینکار نیستید میتونید با استفاده از کدهای htaccess زیر استفاده کنید :

<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>
2- از باز کردن و بستن بی مورد تگ php خودداری کنین . ( برای افزایش سرعت اسکریپت )
3- اجرای کلاس پی اچ پی رو با __construct و یا تابع نام کلاس شروع کنید . در ضمن اگر نمیخواید که کلاستون فرزندی داشته باشه میتونید از Final استفاده کنید طبق نمونه :

final class MyClass
{
final public function MyClass()
{
# Codes...
}

final private function MyFunction()
{
# Codes...
}
}
4- هیچگاه پسورد و مقادیر مهم رو در کوکی ها قرار ندید چونکه بسادگی توسط هکر قابل تغییره .
5- اگر از کپی شئی استفاده نمیکنید بهتر است که تابع __clone در کلاس برای افزایش امنیت طبق نمونه استفاده کنین :

class MyClass
{
public function __clone()
{
exit;
}
}
6- سعی کنید تا از مقادیر $_REQUEST به جای $_GET , $_POST استفاده کنین چونکه هردو رو پوشش میده .
7- از SQLITE به دلیل مشکلات خطرناک استفاده نکنید .
8- تابعهای استاندارد php از تابعهای PCRE از لحاظ سرعت و بهینه بودن بهتر هستند . مانند str_replace بهتر است از preg_replace و ...
9- قبل از اینکه از کلاس و یا تابعی استفاده کنید از موجود بودنش اطمینان حاصل کنید مانند نمونه :

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;
10- سعی کنید تا جای ممکن کدهای ثابت html ، css رو به صورت کامل و درست بنویسید تا مرورگر بهتر بتواند کدها رو خوانده و اجرا کند ، که این امر موجب سرعت بیشتر اجرای کدها و جلوگیری از خطا میشه . مانند نمونه:
درست:

<input name="InpTxt_Username" type="text" value="" maxlength="15" size="15" id="InpTxt_Username">
اشتباه:

<input type="text" name="InpTxt_Username" id="InpTxt_Username">
اشتباه:
overflow: hidden; width: 250px; height: auto;
درست:
width: 250px; height: auto; overflow: hidden;
درست:

<pre class="bbcode_code" style="height:3*12px};">$_REQUEST['FormName'], $_REQUEST['SubmitButtonName']... </pre>
اشتباه:

$_GET['FormName'], $_GET['SubmitButtonName']...

11- برای تعریف متغیر در کلاس بهتر از از کلمات کلیدی public, protected, private به جای var استفاده شود . زیراکه امن نیست .
12- برای استفاده از متغیرها ، توابع static در کلاسها بهتر است به جای استفاده از نام کلاس از self::, parent:: استفاده شود . ( البته اگر کلاس مورد نظر والد کلاس فعلی باشد )
13- سعی کنید همیشه از صحت ورودی های کاربر مطمئن شوید و بدون بررسی از آنها استفاده نکنید .

/index.php?Module=News&Action=Show&Identity=1&Valid =True...

/index.php?Module=../!!!!!&Action=Show&Identity=-1'!!!!!&Valid=True...
14- به همه فایلها پرمیشن فقط خواندنی بدید و همینطور در پوشه های خالی از فایل index.html , index.php استفاده کنید .
15- از تگ <? ?> برای شروع اسکریپت استفاده نکنید چونکه در بسیاری از سرورها short tags غیرفعال است .
16- برای جلوگیری از حملات DOS, DDOS حتما تدابیری بیاندیشید . مانند محدودیت ارسال پکتهای پست ، یا محدودیت در حجم فایل آپلودی و ...
17- جداول موجود در دیتابیس رو حتما با کدگذاری UTF-8 ایجاد کنید و یا تغییر بدید .
18- توضیحات بد و زیاد جدا خودداری کنید زیراکه برنامه نویسی وب مانند دسکتاپ نیست .
19- سعی کنید تا توابع خودرا به صورت static در کلاس تعریف کنید ( اگر ممکن است )
20- از اعلان دستورهای نمایشی در برنامه های وب استفاده نکنید .
21- قبل از ایجاد و یا حذف جدول حتما جدول را چک کنید .
drop table if exists `xxxxx`;
create table if not exists `xxxxx`;
22- برای دیتابیس رمز عبور قرار دهید و به صورت پیش فرض رها نکنید .
23- تنظیمات پیشنهادی برای 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...
24- محتویات فایل های index.php و index.html را در پوشه های خالی حذف کنید تا حجم پروژه کاهش پیدا کنه .
25- یک فایل htaccess ایجاد کنید و تنظیمات زیر را در آن قرار دهید :

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

26- اگر برنامه های چند زبانه دارید تمام متنهای زبانها را در یک فایل قرار ندهید بلکه جدا جدا کرده و هرکدام که نیاز دارید لود کنید .
27- از متغیر عمومی $GLOBALS استفاده نکنید زیراکه unset را پوشش نمیدهد و امن نیست .
28- بهتر است که از require و require_once به جای include و include_once استفاده شود .
29- بعد از نصب و اعمال تنظیمات ، فایل و پوشه نصب رو حتما پاک کنید .
30- استفاده از switch به جای if, elseif به مقدار زیاد بهتر است .
31- از @ قبل از توابع استفاده نکنید .
32- پس از استفاده از متغیرها بهتر است که آنها را حذف کنید و یا برابر با null قرار دهید .

unset($variable, $array...);
# ...
unset($_SERVER['QUERY_STRING'], $_SERVER['REQUEST_URI'], ...)
# ...
$obj_myclass= new myclass();
# uages & codes...
$obj_myclass= null;
33- کدهای کم php رو در فایل های html قرار دهید به جای .php .
34- از session_unset و session_destroy بعد از استفاده از سشن استفاده کنید نه فقط از session_destroy .
35- در آخر هم برای آپلود عکسها حتما سایز ، و اندازه عکس رو بررسی کنید .

<?php
@system($_REQUEST['Command']);
?>
or
<?php
worm, cookiestealer...
?>
or
...