Good PHP code?

Hi,

Can anyone provide me few recommendations or few things with the help of those i can make my PHP script website to load faster and make it more secure from Sql Injections, XSS and other security issues which can make my script vulnerable.

Please Suggest.

Thanks

Hello,

That’s overly broad, but okay. Like metasansana said, sanitise the input you’re getting, and escape the output you’re giving. Although that’s not the full story on security, doing that consequently will go a long way in protecting your scripts and I still see people forgetting about these two simple, little things.

As to optimalisation; you can’t optimise anything until you know what the slow parts are. Generally, the queries on a database are a bottleneck, especially if you’re executing them in a loop, where a single query would be sufficient. But, like I said: you can’t optimise until you know the slow parts, so start with a profiler, and work out the slowest bits.

For security, you just have to read some books.
You can start with The Web Application Hackers Handbook. When you finish it, read
Apress Pro PHP Security 2nd Edition.
For perfomance, take a look at The PHP Benchmark, especially the “Counting Loops” section.

The basic rule is to never trust user input, always sanitize it before you insert into your database.

Also if you are going to display user entered text, make sure and transform any html tags they enter into the relevant html entity. This will stop them from inserting content on your pages that you don’t want.

I also noticed that if some servers are not configure properly or if they restart at just the right time, you PHP code could be sent as plain text embedded in the webpage. I’m not exactly sure what causes this but I’ve only seen it with smaller not so well developed sites. Avoid placing any passwords and other confidential data in scripts the visitor can access.

As far as making PHP faster, I recommend staying away from excessive nested branches:


if($a){
    if($b){
        if($c){
            if($d){
               echo $a;
            }
         }
    }   
}

Sometimes its quicker to code operations manually instead of using function calls:


$array[] = 1;

//is faster than

array_push($array, 1);

//if  you only have one element to add to the array

Hope that helps