Php Best Practices

41
PHP Best Practices PHP Best Practices Bangalore PHP Users Bangalore PHP Users Meetup Meetup 31 31 st st October 2009 October 2009 http://www.meetup.com/Bangalore-PHP- http://www.meetup.com/Bangalore-PHP- Users Users

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

Page 1: 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

Page 2: Php Best Practices

OverviewOverview

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

Page 3: Php Best 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

Page 4: Php Best Practices

Use a Coding Use a Coding StandardStandard

Page 5: Php Best Practices

Why use coding standard?Why use coding standard?

► ConsistencyConsistency► ReadabilityReadability► MaintainabilityMaintainability► CollaborationCollaboration

Page 6: Php Best Practices

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

Page 7: Php Best Practices

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

Page 8: Php Best Practices

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

Page 9: Php Best Practices

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

Page 10: Php Best Practices

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

Page 11: Php Best Practices

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

Page 12: Php Best Practices

ExampleExample

Page 13: Php Best Practices

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

Page 14: Php Best Practices

PHP_CodeSniffer ExamplePHP_CodeSniffer ExampleDefault uses PEAR style coding standard

Page 15: Php Best Practices

PHP_CodeSniffer ExamplePHP_CodeSniffer Example

Page 16: Php Best Practices

DocumentationDocumentation

Page 17: Php Best Practices

DocumentationDocumentation

► Documentation is Documentation is the the

most boring workmost boring work

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

Page 18: Php Best Practices

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.

Page 19: Php Best Practices

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/

Page 20: Php Best Practices

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

Page 21: Php Best Practices

DocumentationDocumentation

phpDocumentor examplephpDocumentor example

Page 22: Php Best Practices

DocumentationDocumentation

phpDocumentor examplephpDocumentor example

Page 23: Php Best Practices

DocumentationDocumentation

Page 24: Php Best Practices

DocumentationDocumentation

Page 25: Php Best Practices

Source ControlSource Control

Page 26: Php Best Practices

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?

Page 27: Php Best Practices

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

Page 28: Php Best Practices

Please enter commit Please enter commit messagemessage

Page 29: Php Best Practices

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

PracticesPractices

Page 30: Php Best Practices

Set register_globals = OffSet register_globals = Off

Page 31: Php Best Practices

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”

Page 32: Php Best Practices

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

Page 33: Php Best Practices

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

Page 34: Php Best Practices

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

Page 35: Php Best Practices

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

Page 36: Php Best Practices

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

Page 37: Php Best Practices

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'])

Page 38: Php Best Practices

►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

Page 39: Php Best Practices

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

Page 40: Php Best Practices

Questions?Questions?

Thanks for your attentionThanks for your attention

Page 41: Php Best Practices

ContactContact

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

► Contact optionsContact options Email:[email protected]/Email:[email protected]/

[email protected][email protected] Blog: http://ansarahmed.blogspot.comBlog: http://ansarahmed.blogspot.com

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