Php Best Practices

Post on 15-Jan-2015

2.446 views 0 download

Tags:

description

Covered some of the Best Practices. Reference: http://www.brandonsavage.net/essential-ini-settings/ http://shiflett.org/blog/2005/feb/my-top-two-php-security-practices http://www.php.net/manual/en/security.php

Transcript of Php Best Practices

PHP Best PracticesPHP Best Practices

Bangalore PHP Users MeetupBangalore PHP Users Meetup

3131stst October 2009 October 2009http://www.meetup.com/Bangalore-PHP-Usershttp://www.meetup.com/Bangalore-PHP-Users

OverviewOverview

► About this talkAbout this talk► Coding StandardCoding Standard► DocumentationDocumentation► Sub VersionSub Version► General PracticesGeneral Practices

About this talkAbout this talk

► Common good practises for coding PHPCommon good practises for coding PHP► Tips for clean PHP codeTips for clean PHP code► How to avoid common mistakesHow to avoid common mistakes► Tricks and TipsTricks and Tips► Tools to ease your workTools to ease your work

Use a Coding Use a Coding StandardStandard

Why use coding standard?Why use coding standard?

► ConsistencyConsistency► ReadabilityReadability► MaintainabilityMaintainability► CollaborationCollaboration

Okay, I’LL Create one…Okay, I’LL Create one…

Learn from othersLearn from others

Don’t invent your own standard. All the Don’t invent your own standard. All the issue has been debated to death.issue has been debated to death.

Use an established standardUse an established standard

Stick to an standard you establish, don’t Stick to an standard you establish, don’t mixmix

What choices exist?What choices exist?

► PEAR Coding StandardsPEAR Coding Standardshttp://pear.php.net/manual/en/standards.phphttp://pear.php.net/manual/en/standards.php

► Zend Framework Coding StandardsZend Framework Coding Standardshttp://framework.zend.com/manual/en/coding-standard.htmlhttp://framework.zend.com/manual/en/coding-standard.html

► eZcomponents Coding StandardseZcomponents Coding Standards

http://ez.no/products/ez_publish/documentation/development/standahttp://ez.no/products/ez_publish/documentation/development/standards/phprds/php

Some Zend Framework Some Zend Framework standardsstandards

►Derived from PEAR standardsDerived from PEAR standards►One class, one fileOne class, one file►Underscore in class name map to Underscore in class name map to

directory separators:directory separators:

Zend_Controller_Action:Zend_Controller_Action:

Zend/Controller/Action.phpZend/Controller/Action.php

Some Zend Framework Some Zend Framework standardsstandards

Naming conventions:Naming conventions:►Class name are MixedCase – Zend_PdfClass name are MixedCase – Zend_Pdf►Method name are camelCase - Method name are camelCase -

filterInput()filterInput() ►Constants are ALL_CAPS – SET_TIMEConstants are ALL_CAPS – SET_TIME►Properties and variables are camelCaseProperties and variables are camelCase►Private and protected member are Private and protected member are

_underscorePrefixed_underscorePrefixed

Some Zend Framework Some Zend Framework standardsstandards

Layout Conventions:Layout Conventions:►No closing ?> tag for files containing No closing ?> tag for files containing

only codeonly code► Indentation: spaces only, no tabs;4 Indentation: spaces only, no tabs;4

spaces per level of indentationspaces per level of indentation►No shell style comments(#)No shell style comments(#)►Keep lines no more than 75-80 Keep lines no more than 75-80

characters longcharacters long

ExampleExample

Any tool to check coding Any tool to check coding standards?standards?

PHP_CodeSniffer is one such tool:PHP_CodeSniffer is one such tool:► PHP_CodeSniffer is a PHP5 script that PHP_CodeSniffer is a PHP5 script that

tokenises and "sniffs" PHP, JavaScript and tokenises and "sniffs" PHP, JavaScript and CSS files to detect violations of a defined CSS files to detect violations of a defined coding standard. coding standard.

► Your own coding standards.Your own coding standards.► Subversion integrationSubversion integration►

http://pear.php.net/manual/en/package.php.http://pear.php.net/manual/en/package.php.php-codesniffer.phpphp-codesniffer.php

PHP_CodeSniffer ExamplePHP_CodeSniffer ExampleDefault uses PEAR style coding standard

PHP_CodeSniffer ExamplePHP_CodeSniffer Example

DocumentationDocumentation

DocumentationDocumentation

► Documentation is Documentation is the the

most boring workmost boring work

► Don't have time!Don't have time!

DocumentationDocumentation

►You don’t have time to code?You don’t have time to code?►Re-read your code 6 month after you Re-read your code 6 month after you

wrote it!wrote it!►Think about people who have to use Think about people who have to use

your codeyour code►Code should communicate its purposeCode should communicate its purpose►The better the names, the fewer The better the names, the fewer

comments.comments.

What choices exist?What choices exist?

►Source DocumentationSource Documentation phpDocumentorphpDocumentor

http://phpdoc.orghttp://phpdoc.org DoxygenDoxygen

http://www.stack.nl/~dimitri/doxygen/http://www.stack.nl/~dimitri/doxygen/

►End User DocumentationEnd User Documentation DocBookDocBook

http://www.docbook.org/http://www.docbook.org/

DocumentationDocumentation

phpDocumentorphpDocumentor► Derived from Javadoc, written in PHP.Derived from Javadoc, written in PHP.► phpDocumentor tags are the most used phpDocumentor tags are the most used

standard for generating documentation from standard for generating documentation from php source codephp source code

► Other documentation generators, such as Other documentation generators, such as Doxygen, support these same tags. Don’t Doxygen, support these same tags. Don’t invent your own tags.invent your own tags.

► Supported by a number of different IDEs. Supported by a number of different IDEs. Zend Studio is perhaps the most prevalent.Zend Studio is perhaps the most prevalent.

► Command line or web interface.Command line or web interface.► Not only HTML, but also .chm or PDFNot only HTML, but also .chm or PDF

DocumentationDocumentation

phpDocumentor examplephpDocumentor example

DocumentationDocumentation

phpDocumentor examplephpDocumentor example

DocumentationDocumentation

DocumentationDocumentation

Source ControlSource Control

Why do I need it?Why do I need it?

►How do i know if somebody did How do i know if somebody did something?something?

►How do others know i did something?How do others know i did something?►How do i get my updates from others?How do i get my updates from others?►How do i push my updates out to How do i push my updates out to

others?others?►Do we have the old version?Do we have the old version?►What changed?What changed?

What choices exist?What choices exist?

► Distributor Source Control:Distributor Source Control:Developers works on their own repositories Developers works on their own repositories and share changesetsand share changesets GitGit DarcsDarcs ArchArch

► Non-Distributed Source ControlNon-Distributed Source ControlDeveloper work on local checkouts, and Developer work on local checkouts, and check in to a central repositorycheck in to a central repository SubversionSubversion

Please enter commit Please enter commit messagemessage

General PracticesGeneral Practices► Essential INI SettingsEssential INI Settings► My Top Two PHP SecurityMy Top Two PHP Security

PracticesPractices

Set register_globals = OffSet register_globals = Off

Set magic_quotes = Off Set magic_quotes = Off

There are three php.ini settings that relate to magic_quotes: There are three php.ini settings that relate to magic_quotes:

; Magic quotes; Magic quotes;;

; Magic quotes for incoming GET/POST/Cookie data.; Magic quotes for incoming GET/POST/Cookie data.magic_quotes_gpc = Offmagic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.magic_quotes_runtime = Offmagic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').; Use Sybase-style magic quotes (escape ' with '' instead of \').magic_quotes_sybase = Offmagic_quotes_sybase = Off

Example:- “This is my code’s string” gets converted to “This is my code\’s string”Example:- “This is my code’s string” gets converted to “This is my code\’s string”

Set error_reporting = E_ALL | Set error_reporting = E_ALL | E_STRICTE_STRICT

► STRICT messages will help you to use STRICT messages will help you to use the latest and greatest suggested the latest and greatest suggested method of coding, for example warn method of coding, for example warn you about using deprecated functions. you about using deprecated functions.

►Available since PHP 5.0Available since PHP 5.0►Production:Production:

display_errors = Offdisplay_errors = Off log_errors = onlog_errors = on error_log = path/logs/php_error.logerror_log = path/logs/php_error.log

Set short_open_tag = 0Set short_open_tag = 0

► If you want to use PHP in combination with If you want to use PHP in combination with XML, you can disable this option in order to XML, you can disable this option in order to use <?xml ?> inline.use <?xml ?> inline.

► Otherwise, you can print it with PHP, for Otherwise, you can print it with PHP, for example: <?php echo '<?xml example: <?php echo '<?xml version="1.0"?>'; ?>version="1.0"?>'; ?>

► Safe to use <?php ?> tagSafe to use <?php ?> tag► Might be deprecated, But no news yet on Might be deprecated, But no news yet on

php.netphp.net► Good practice is to use <?php ?> tagGood practice is to use <?php ?> tag

No direct access to the No direct access to the php.iniphp.ini

Use htaccess directive:Use htaccess directive:► php_flagphp_flag

php_flag is reserved for boolean values, like php_flag is reserved for boolean values, like register_globals and magic_quotes_gpc.register_globals and magic_quotes_gpc.

example:- php_flag register_globals Offexample:- php_flag register_globals Off ► php_value php_value

php_value for things that are not boolean, php_value for things that are not boolean, like error_reporting and error_log.like error_reporting and error_log.

example:- php_value error_log /var/www/logs/php_errors.logexample:- php_value error_log /var/www/logs/php_errors.log

My Top Two PHP SecurityMy Top Two PHP Security Practices Practices

Top Two PHP Security Practices, Top Two PHP Security Practices, expressed inexpressed in

four words:four words:► Filter inputFilter input► Escape outputEscape output

- - Chris ShiflettChris Shiflett

Filter InputFilter Input

►Don't trust external data, The rule #1 of Don't trust external data, The rule #1 of every developer Should be "Filter All every developer Should be "Filter All Foreign Data"Foreign Data"

►With the delivery of PHP 5.2.0, this got a With the delivery of PHP 5.2.0, this got a lot easier, because PHP included, by lot easier, because PHP included, by default, the Filter library. default, the Filter library.

►Manual - http://www.php.net/filterManual - http://www.php.net/filter►Downloads - http://pecl.php.net/get/filterDownloads - http://pecl.php.net/get/filter►Filter homepage - Filter homepage -

http://pecl.php.net/filterhttp://pecl.php.net/filter

Filter library examplesFilter library examples► $email   = $email   = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_EMAIL);filter_input(INPUT_POST, 'name', FILTER_VALIDATE_EMAIL);

► $age     = $age     = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);

► $url     = $url     = filter_input(INPUT_COOKIE, 'url', FILTER_VALIDATE_URL); filter_input(INPUT_COOKIE, 'url', FILTER_VALIDATE_URL); 

► $raw_msg = filter_input(INPUT_POST, 'msg', FILTER_UNSAFE_RAW); $raw_msg = filter_input(INPUT_POST, 'msg', FILTER_UNSAFE_RAW); ► $options = $options = array('options'=> array('min_range'=>7, 'max_range'=>77));array('options'=> array('min_range'=>7, 'max_range'=>77));

$age$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT,$options); = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT,$options);

► filter_has_var(INPUT_POST, 'submit') filter_has_var(INPUT_POST, 'submit')

is same as is same as

isset($_POST['submit'])isset($_POST['submit'])

►With properly filtered input, you're With properly filtered input, you're already pretty well protected against already pretty well protected against malicious attacks. malicious attacks.

►The only remaining step is to escape it The only remaining step is to escape it such that the format of the input such that the format of the input doesn't accidentally interfere with the doesn't accidentally interfere with the format of the SQL statement. format of the SQL statement.

INSERT INTO MyTable (MyColumn) VALUES ('My Dear Aunt Sally's Picnic INSERT INTO MyTable (MyColumn) VALUES ('My Dear Aunt Sally's Picnic

Basket')Basket')

Escaping OutputEscaping Output

Escaping OutputEscaping Output

Use dedicated escaping function provided by the Use dedicated escaping function provided by the database database

interface:interface:► MySQLMySQL

mysql_real_escape_string()mysql_real_escape_string()► PostgreSQLPostgreSQL

pg_escape_string()pg_escape_string() pg_escape_bytea()pg_escape_bytea()

► SQLiteSQLite sqlite_escape_string()sqlite_escape_string()

► Other databasesOther databases ADOdb, qstr function - http://adodb.sourceforge.net/ADOdb, qstr function - http://adodb.sourceforge.net/ PEAR, quote function - http://pear.php.net/PEAR, quote function - http://pear.php.net/

http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-stringhttp://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string

Questions?Questions?

Thanks for your attentionThanks for your attention

ContactContact

► Slides will be on slideshareSlides will be on slideshare http://slideshare.net/ansarahmedhttp://slideshare.net/ansarahmed

► Contact optionsContact options Email:ansarahmed8@gmail.com/Email:ansarahmed8@gmail.com/

ansarahmed_8@yahoo.co.inansarahmed_8@yahoo.co.in Blog: http://ansarahmed.blogspot.comBlog: http://ansarahmed.blogspot.com

► Follow me on twitter:Follow me on twitter: @ansarahmed@ansarahmed @phpbangalore@phpbangalore