26. Avoid direct SQL query , abstract it
$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')"; $db->query($query); //call to mysqli_query()
The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:
- All values have to be escaped everytime manually
- Manually verify the sql syntax everytime.
- Wrong queries may go undetected for a long time (unless if else checking done everytime)
- Difficult to maintain large queries like that
Solution: ActiveRecord
It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.
A very simple example of an activerecord insert function can be like this :
function insert_record($table_name , $data) { foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query); } //data to be inserted in database $data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone); //perform the INSERT query insert_record('users' , $data);
The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).
This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.
27. Cache database generated content to static files
Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.
Benefits :
- Save php processing to generate the page , hence faster execution
- Lesser database queries means lesser load on mysql database
28. Store sessions in database
File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.
Storing session in database makes many other things easier like:
- Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time
- Check online status of users more accurately
29. Avoid using globals
- Use defines/constants
- Get value using a function
- Use Class and access via $this
30. Use base url in head tag
Quick example :
<head> <base href="http://www.domain.com/store/"> </head> <body> <img src="happy.jpg" /> </body> </html>
The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.
Lets take an example
www.domain.com/store/home.php
www.domain.com/store/products/ipad.php
In home.php the following can be written :
<a href="home.php">Home</a> <a href="products/ipad.php">Ipad</a>
But in ipad.php the links have to be like this :
<a href="../home.php">Home</a> <a href="ipad.php">Ipad</a>
This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.
<head> <base href="http://www.domain.com/store/"> </head> <body> <a href="home.php">Home</a> <a href="products/ipad.php">Ipad</a> </body> </html>
Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php
31. Manage error reporting
error_reporting is the function to use to set the necessary level of error reporting required.
On a development machine notices and strict messages may be disabled by doing.
ini_set('display_errors', 1); error_reporting(~E_NOTICE & ~E_STRICT);
On production , the display should be disabled.
ini_set('display_errors', 0); error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.
After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.
ini_set('log_errors' , '1'); ini_set('error_log' , '/path/to/errors.txt'); ini_set('display_errors' , 0); error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
Note :
1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there.
2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors.
3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).
4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched.
5. Dont set error_reporting to 0. It will not log anything then.
Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.
Set 'display_errors=On' in php.ini on development machine
On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set)
This is because any compile time fatal errors will now allow ini_set to execute , hence no error display
and a blank WHITE page.
Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.
Set 'display_errors=Off' in php.ini on production machine
Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.
32. Be aware of platform architecture
The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.
On a 64 bit machine you can see such output.
$ php -a Interactive shell php > echo strtotime("0000-00-00 00:00:00"); -62170005200 php > echo strtotime('1000-01-30'); -30607739600 php > echo strtotime('2100-01-30'); 4104930600
But on a 32 bit machine all of them would give bool(false). Check here for more.
What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.
33. Dont rely on set_time_limit too much
If you are limiting the maximum run-time of a script , by doing this :
set_time_limit(30); //Rest of the code
It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit.
So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.
34. Make a portable function for executing shell commands
system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.
A better solution :
/** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec */ function terminal($command) { //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var); } terminal('ls');
The above function will execute the shell command using whichever function is available , keeping your code consistent.
35. Localize your application
Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.
36. Use a profiler like xdebug if you need to
Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.
Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.
37. Use plenty of external libraries
An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.
Few popular libraries are :
- mPDF - Generate pdf documents, by converting html to pdf beautifully.
- PHPExcel - Read and write Excel files
- PhpMailer - Send html emails with attachments easily
- pChart - Generate graphs in php
38. Have a look at phpbench for some micro-optimisation stats
If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.
39. Use an MVC framework
Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.
- Clean separation of php and html code. Good for team work, when designers and coders are working together.
- Functions and functionalities are organised in classes making maintenance easy.
- Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc.
- Is a must when writing big applications
- Lots of tips, techniques, hacks are already implemented in the framework
40. Read the comments on the php documentation website
The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.
They contain user feedback, expert advice and useful code snippets. So check them out.
41. Go to the IRC channel to ask
The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!
42. Read open source code
Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.
The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more
1. Codeigniter
2. WordPress
3. Joomla CMS
43. Develop on Linux
If you are already developing on windows, then you might give Linux a try. My favorite is ubuntu. Although this is just an opinion but still I strongly feel that for development linux is a much better environment.
Php applications are mostly deployed on linux (LAMP) environments. Therefore, developing in a similar environment helps to produce a robust application faster.
Most of the development tools can be very easily installed from synaptic package manager in Ubuntu. Plus they need very little configuration to setup and run. And the best thing is, that they all are free.
About the item 28 “Store sessions in database”, I have a serious problem to develop an free-of-errors application in this case: if I store logged users in a database to verify duplicate logins, may occurs the cpu/tablet reset with the user using the application, and the information about the user will stay on the database, and the user will not be able to login until the information be cleared. What´s the better way in this case? I have doubt if setting a time limit to disconnect users without activities after, for example, 10 minutes.
Sugestions?
the good MVC framework is Yii Framework.(http://www.yiiframework.com/)
Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. It can reduce your development time significantly.
Thanks for sharing, useful post. I like the number 34 approach and i use it a lot, but there is something that bugs me to end and I can’t figure it out. Lets say the code is like:
exec(“php-cli $path_to_file > /dev/null 2>/dev/null &”);
Some servers that are configured differently will require the full path to php binary for the shell command to work. How can I get that before hand to ensure compatibility? (obviously asking the host is not possible)
Thanks.
when running any php script from commandline, the full path should always be provided.
the full path should be set before hand inside the application somewhere.
Very useful article, thanks!
Just one thing on #26: I think there’s a typo on the variable in the query. It should be “INSERT INTO {$table_name} … “
Never ever turn on display errors in production, instead log those errors
Reading open source code is not always a good idea…look at wordpress, joomla, phpnuke…code is nearly piece of joke…so choose wisely which u read
I don’t think 31 is a very good idea, it may expose information you don’t want exposed and it will make debugging things harder by only showing fatal errors. I would suggest:
ini_set(‘display_errors’, false);
error_reporting(E_ALL);
agree with your point , and updated the post.
On “34. Make a portable function for executing shell commands”, what about backticks? http://php.net/manual/en/language.operators.execution.php
backticks are the same as shell_exec
“Develop on Linux” is just plain … you know.
Most of the best tools are available for Windows too and im developing on Windows for years without problems.
Anyway it’s true that most Webservers are running with Linux but there are very few issues (strict file names) that are causing problems.
Yes, there are plenty of good tools available on windows too , but linux does have some cool things.
All text editors on linux have code highlighting , all file browsers are can work with ftp:// urls making working on live server very easy.
The terminal is all powerful , with inbuilt ssh , and text editors to directly edit files on server.
File permission system is identical to that of server so problems are caught early , making the code move in the right direction.
“all file browsers are can work with ftp:// urls making working on live server very easy.”
If you’re working on a live server you’re doing it wrong. Use SVN :)
just my 2 cents as many people / beginners might read this. Need to give them good advice from the start ;)
On your MySQL query, I would use the “INSERT INTO…SET” way. This will allow to to quickly change the query into a UPDATE and also make it a lot easier to troubleshoot. Other things are to use back ticks around table and DB names.
INSERT INTO users(name , email , address , phone) VALUES(‘$name’ , ‘$email’ , ‘$address’ , ‘$phone’)”;
would become:
INSERT INTO `users`
SET `name` = ‘$name’,
`email` = ‘$email’,
`address` = ‘$address’,
`phone` = ‘$phone’;
Of course I wouldn’t use this directly. I would use PDO parameterized queries to better protect against SQL injections.
Nice argument EllisGL, that’s what I would like to add to this post.
You could build a function to your database class like this:
class MyDatabase {
[…]
insert($strTable, $arData){
if(!is_array($arData) OR count($arData) == 0)
return false;
$strInsertString = “”;
foreach($arData as $strKey => $strValue)
$strInsertString .= $strKey.”='”.$this->real_escape($strValue).”‘,”;
$strInsertString = rtrim($strInsertString, “,”);
return $this->query(“INSERT INTO “.$this->real_escape($strTable).” SET “.$strInsertString);
}
}
@Richard: A couple issues with that. Your strKey and strTable are not back ticked and may cause issues, specially if you use table or column names like “name”. Also if you have a WHERE statements, you would have to deal with those. I use a PDO wrapper that allows me to do the following:
class Query_Tablename extends Db_Connect_Dbname
{
public static function getSomethingFromTables($tablename_id = FALSE, $offset = 0, $limit = 10)
{
$SQL = self::statement();
$SQL->sql(‘SELECT tn.*,’)
->sql(‘ tn2.cname’)
->sql(‘FROM `tablename` tn’)
->sql(‘ JOIN `tbalename2` tn2’)
->sql(‘ ON tn2.tablename2_id = tn.tablename_id’)
->sql(‘WHERE (0 = ? OR tn.tablename_id = ?)’)->sBoolInt($tablename_id)->sInt($tablename_id)
->sql(‘LIMIT ? OFFSET ?’)->sInt($limit)->sInt($offset); // use sprintf() functionality, since I need to add the “(int)” stuff.
//$SQL->dump();
return self::selectMany($SQL);
}
}
The wrapper (which isn’t publicly available at this time and I haven’t seen anything like it) does automatic binding, but has a couple issues I need to work out.
You are right with the WHERE clauses for SELECT-Queries, but for INSERT-Queries, you don’t realy need a where clause ;))
The issues with the table names are right, but it’s one of the most important thinks by setting up a databse strukture without table names like that!
To your wrapper:
I don’t realy like Database Classes with queries like that. OOP is great, but I never got the point of this strange and big sql string adapters. Why should it be faster/easier/clearer to use
$objQuery->sql(“SELECT *”)->sql(“FROM TABLE”)->sql(“WHERE foo=bar”)?
Insteat of:
$strQuery = “SELECT * FROM TABLE WHERE foo=bar”;
$objQuery->sql($strQuery);
or
$objQuery->sql(“SELECT * FROM TABLE WHERE foo=bar”);
:))
I’ve taken that wrapper I talked about in 2012 and re-wrote it https://github.com/ellisgl/GeekLab-GLPDO2