Top 10 PHP Techniques That Will Save You Time and Effort
Posted by Spyros in PHP Programming, tags: how to code php, php advice, php best, php techniques, php tips, php tricks, top 10 php
What would happen if you tried to use a mirror as a surfboard ? Well, you may succeed in taming the waves for a little while, or even a big while, but deep inside, you know that this is not really the right way to do it. Weird as it may sound, the same principals apply to php programming. I’ve heard of people trying to learn PHP by studying it for like a weekend or more, but allow me to say, this is a pretty bad approach to learning this programming language.
Why is The Learning PHP Process Different Than Any Other Programming Language ?
By nature, PHP is all about knowing what to do. If you have the knowledge on how to do something in PHP, actually doing it is most of the times really really easy. I would actually pay to know some of these things beforehand. In PHP, doing things the way you think them will most probably result in doing them the wrong way. Not because you’re a bad programmer, but because there are some standard tricks of the trade that you cannot really avoid using, if you want to write good and maintanable code. Let’s talk about these 10 techniques that you really need to know about :
1. How to Properly Create a Website Index Page
Creating your website index page is the first thing to do for every website that you create. I’ve actually created a post that will help you properly create a website index page.
2. Use the Request Global Array to Grab Data
There is actually no reason to use $_GET and $_POST arrays to grab values. $_REQUEST, is another global array that fetches you either a get or form request. Therefore, it’s most times more convenient to use something like this to parse data :
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 0;
3. Debugging PHP is About var_dump
If you’re looking for php debugging techniques, i have to say that var_dump is most times the way to go about it. This command is all you need to echo php information. There shouldn’t really be many cases where you need anything more than dumping values in PHP, in order to debug your code.
4. PHP Handles The Code Logic, Smarty Handles The Presentation
I think i’ve said this many times before, but Smarty usage (or other template system), is critical for creating organized PHP code. Learn to use smarty as a template engine for your websites, it will pay off, i promise.
5. When You Absolutely Need Global Values, Create a Config File
It is a bad practice to create global values for everything. There are limited cases where you would actually need to do so. Doing it for database tables or database connection information is a good idea, but do not use global variables throughout your PHP code. Moreover, it is always a better idea to keep your global variables at a single config.php file.
6. If NOT Defined, Access Denied !
If you’re creating your pages the correct way, there will absolutely no reason for anybody to access any other php page other than index.php or home.php. The idea is that once index.php is accessed, you utilize get variables in order to open the needed pages. Your index page should contain something like :
define('yourPage',1);
Then, your other pages should contain this :
if (!defined('yourPage')) die('Access Denied');
What this does, is preventing direct access to your other php pages. Therefore, any user who tries to access your other web pages, not through index.php, gets an “Access Denied” message.
7. Create a Database Class
If you’re doing database programming (pretty common in PHP), it would be a very good idea to create a database class to handle any database management functions. A good way to do it is by creating functions like :
public function dbExec($query)
{
$result = $this->db->exec($query);
if (PEAR::isError($result))
errorRedirect($result->getMessage(), true);
else
return $result;
}
This is an example function from an actual project i’m creating. This one just receives a query and executes it. It also handles any errors that may occur. You could also include sanitization code here, but i prefer to do it using a sanitization function like :
// checks if arguments given are integer values not less than 0 - has multiple arguments
function sanitizeInput()
{
$numargs = func_num_args();
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
if (!is_numeric($arg_list[$i]) || $arg_list[$i] < 0)
errorRedirect("Unexpected variable value", true);
}
}
8. A php File Handles Input, a class.php File Handles Functionality
It is pretty important that you learn not to mess the code that retrieves user input and redirects it to any functions, with those actual functions. The idea is pretty simple. The php file gets any input that we need and then redirects execution to a function residing to the class file. For example, let’s suppose that a url is like “index.php?page=profile&action=display”. The profile.php file retrieves the url and gets that action is “display”. Then, using a simple switch, we execute the actual display function like :
require_once PROJECTROOT.'libs/messages.class.php';
$message = new Message();
switch ($action)
{
case 'display':
$message->display();
break;
...
Again, this is part of a project that i create. You see that i include the messages class and then initiate the switch check. $message is just an object that is used to call functions inside the class.
9. Know Your SQL and Always Sanitize
As i mentioned before, a database is 99% of times important for any php created website. Therefore, you need to know many things about how to use sql properly. Learn to combine tables and more advanced techniques. I promise there will be mysql tutorials soon in codercaste.com. Let me present you an example of a function that uses mySQL and sanitazes using the function seen on point #7 :
private function getSentMessages($id)
{
$this->util->sanitizeInput($id);
$pm_table = $GLOBALS['config']['privateMsg'];
$users = $GLOBALS['config']['users'];
$sql = "SELECT PM.*, USR.username as name_sender FROM $pm_table PM, $users USR
WHERE id_sender = '$id' AND sender_purge = FALSE AND USR.id = PM.id_receiver AND is_read = TRUE
ORDER BY date_sent DESC";
$result = $this->dbQueryAll($sql);
return $result;
}
At first, we sanitize the user input (the message id at this point, that is passed through a GET variable) and then we execute our sql command. Notice the usage of sql here. You need to learn how to use aliases and combine tables.
10. When You Need Just an Object, Use a Singleton Pattern
It happens pretty often in PHP that we just need a single object created one time and then used globally throughout our whole program. A good example of this is the smarty variable that has to be initialized once and then is used all over the place. A good way to do that is a Singleton pattern, where an object is just created once and for all. The way to do this is like :
function smartyObject()
{
if ($GLOBALS['config']['SmartyObj'] == 0)
{
$smarty = new SmartyGame();
$GLOBALS['config']['SmartyObj'] = $smarty;
}
else
$smarty = $GLOBALS['config']['SmartyObj'];
return $smarty;
}
Notice that we have a global smarty variable (initialized in config.php in example) and if it equals 0, we go about creating a new smarty object. If not, it means that the object is already created and we just need to return it.
Hope these 10 techniques are as helpful to you as they are for me and i would really like to listen to what you think is your most important PHP technique.

Entries (RSS)
Don’t agree with # 2, we should receive specific data as needed.
Nice post indeed.
Hey Musa,
Actually, the specificity of data depends on the name of the variable alone. There is no security threat in using $_REQUEST instead of $_POST or $_GET.
thank you for your comment
Since you always just need to get input, $_REQUEST is all you need.
Minor point:
4. PHP Handles The Code Logic
Just a little typo.
Although using $_REQUEST doesn’t pose a security threat per say, it does mean that data you expect to be submitted via POST could be entered in the URL.
It’s worth mentioning that you should always sanitize your input data, never trust user input, and then using $_REQUEST will post no real threat.
@Boolean Value
Thank you, fixed that
@Matthew Lanham
Exactly Matthew. The data can still be submitted via the URL, but i don’t think that this is much of a problem. I tend to only use $_REQUEST for sake of simplicity, without having any problems.
And of course, you’re right about sanitizing data. This is very important. In a future post i will write about proper sanitization.
I’m not a big fan of Smarty, or any other templating language. PHP was invented to be a templating system, so it’s not a sin to mix HTML and PHP together(as believed by many) as long as you keep the business and presentation logic separate.
just use a php MVC framework like codeigniter.
.-= Geshan Manandhar´s last blog ..5 reasons why you should choose YIPL for your next web project =-.
About point 3. Debugging PHP is About var_dump , I completely disagree.
Setting up a debugger like XDebug with your IDE will save you heaps of time.
Adding var_debug() statements is way to cumbersome …
Or maybe try one of the myriads of php frameworks out there
When I saw point #2, I knew there would be a borderline debate.
While I agree that using $_REQUEST alone doesn’t introduce security problems, I (personally) would still use either POST, or GET.
You could actually have the same parameter name in both, with different values. (Not that you ever would, but it is certainly possible).
$_REQUEST would only contain the value from the POST.
Also, If you actually “need” to know that a form was submitted via post, you would have to look at _POST.
Thank you for the comments guys. It’s ok to disagree. I suppose everyone is talking about his/her own experiences
For instance, i don’t really find any reason to know where data comes from, either POST or GET. If you find any REAL reason on why this is not so, please enlighten me.
Now, i don’t really like IDEs to code PHP. I think it’s redundant and i’ve found that var_dump is just enough.
And of course, Smarty is an incredibly useful tool that takes about an hour to learn at most.
Still, these are all just ideas and personal preferences.
I do not agree with REQUEST for POST and GET.
and why to write own db abstraction layer if there are classes available like pear DB!
.-= Satya Prakash´s last blog ..Masthead background color experimentation =-.
Satya, i’m not writing my own abstraction layer, but rather a more convenient way to use mysql functions along with sanitization.
I notice that many people disagree about $_REQUEST, but none gives a good argument against its usage :O
It’s good to disagree, but not just to disagree. Provide a good reason and i will follow.
Wow.
$_REQUEST bickering aside, your use of the singleton pattern is clearly wrong. You’ve not addressed the fact that there’s nothing stopping anyone making a new SmartyGame object anywhere, so it’s not a singleton.
Alex, this is a Singleton Pattern used to create a one time object. It’s not created with multiple objects in mind.
In my case, i restrict usage to one object alone that is immutable. Therefore, it is a Singleton implementation. Not the one you have in mind, but still. But i agree that one could argue with what you say.
Still, if i just use an object to coordinate class actions globally, i’m using a Singleton (or at least Singleton-like) pattern. You don’t create a Singleton Pattern in order to stop others from creating instances because, you’re behind the program. So, as long as you do not create an interface, doing what i did is Singleton convenient.
If you need to argue that this is not STRICTLY Singleton, i would agree. However, i do exactly what a strict singleton implementation would offer me. Isn’t that clear ?
[...] his full post here. If you think I may have been too harsh, or not harsh enough, on him, leave a comment. Share [...]