Tuesday, May 17, 2016

60 PHP Tips and Tricks You Must Know

Today I am going to discuss some useful (60 to be more precise) PHP tips and tricks which will make your life as a PHP designer more easy.Today is a special day as today this blog is celebrating its first anniversary.Today this blog is 1 year old..So this post is dedicated to all of you who have made this blog so very successful and eagerly wait for every single update.So lets begin with the tips and tricks.

 1. PHP Output Buffering

I have come across cases where something was being output to the screen that I didnt want (at least at that point, or maybe not at all). A common example of this is if you have a function or a script that echoes out a string, but you are using the code in that instance where you dont want it to print to the screen at that point (when using a template system or framework system, for example). In this case you would still want to be able to reuse the code, but just prevent anything from being printed out at that exact point. This will make more sense if you look at this simple example:
<?php
ob_start();

echo Print to the screen!!!;
$getContent = ob_get_contents();

ob_end_clean();

// Do whatever you want...

// Do something with the printed content (only if you want)...
echo Now: . $getContent;

You probably were familiar with at least some of these, but I hope that

someone will find this list useful in some capacity. :)
2. Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.

3. Use sprintf instead of variables contained in double quotes, it’s about 10x faster.

4. Use echo’s multiple parameters (or stacked) instead of string concatenation.

5. Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.

 6. Unset or null your variables to free memory, especially large arrays.

 7. Avoid magic like __get, __set, __autoload.

 8. Use require() instead of require_once() where possible.

 9. Use full paths in includes and requires, less time spent on resolving the OS paths.

 10. require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.

 11. Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().

 12. PCRE regex is quicker than EREG, but always see if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead.

 13. When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.

 14. str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace.

 15. “else if” statements are faster than select statements aka case/switch.

 16. Error suppression with @ is very slow.

17. To reduce bandwidth usage turn on mod_deflate in Apache v2 or for Apache v1 try mod_gzip.

18. Close your database connections when you’re done with them.

19. $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.

 20. Use tags when declaring PHP as all other styles are depreciated, including short tags.

 21. Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.

 22. PHP scripts are be served at 2-10 times slower by Apache httpd than a static page. Try to use static pages instead of server side scripts.

 23. PHP scripts (unless cached) are compiled on the fly every time you call them. Install a PHP caching product (such as memcached or eAccelerator or Turck MMCache) to typically increase performance by 25- 100% by removing compile times. You can even setup eAccelerator on cPanel using EasyApache3.

24. An alternative caching technique when you have pages that don’t change too frequently is to cache the HTML output of your PHP pages. Try Smarty or Cache Lite.

 25. Use isset where possible in replace of strlen. (ie: if (strlen($foo) < 5) { echo “Foo is too short”; } vs. if (!isset($foo{5})) { echo “Foo is too short”; } ).

 26. ++$i is faster than $ i++, so use pre-increment where possible.

 27. Make use of the countless predefined functions of PHP, don’t attempt to build your own as the native ones will be far quicker; if you have very time and resource consuming functions, consider writing them as C extensions or modules.

28. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview.

29. Document your code.

 30. Learn the difference between good and bad code.

 31. Stick to coding standards, it will make it easier for you to understand other people’s code and other people will be able to understand yours. 32. Separate code, content and presentation: keep your PHP code separate from your HTML.

 33. Don’t bother using complex template systems such as Smarty, use the one that’s included in PHP already, see ob_get_contents and extract, and simply pull the data from your database.

 34. Never trust variables coming from user land (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML.

 35. For security reasons never have anything that could expose information about paths, extensions and configuration, such as display_errors or phpinfo() in your webroot.

 36. Turn off register_globals (it’s disabled by default for a reason!). No script at production level should need this enabled as it is a security risk. Fix any scripts that require it on, and fix any scripts that require it off using unregister_globals(). Do this now, as it’s set to be removed in PHP6.

 37. Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5 hash. 38. Use ip2long() and long2ip() to store IP addresses as integers instead of strings.

 39. You can avoid reinventing the wheel by using the PEAR project, giving you existing code of a high standard.

 40. When using header(’Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible.

 41. In OOP, if a method can be a static method, declare it static. Speed improvement is by a factor of 4.

42. Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable. 43. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

44. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

45. Just declaring a global variable without using it in a function slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.

 46. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.

 47. Methods in derived classes run faster than ones defined in the base class.

 48. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.

 49. Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory.

50. Never trust user data, escape your strings that you use in SQL queries using mysql_real_escape_string, instead of mysql_escape_string or addslashes. Also note that if magic_quotes_gpc is enabled you should use stripslashes first.

 51. Avoid the PHP mail() function header injection issue.

 52. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.

 53. RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English.

 54. Counting Characters in a String To do this, Ive usually just used the function strlen(). However, there is a faster method. Take a look at the following code example:
<?php
$string = testing;

if(isset($string[6]))
echo "The string $string is at least 7 characters long.";
else
echo "The string $string is less than 7 characters long.";
You treat the $string value like an array by passing an integer value to isset(). If that number plus one is greater than or equal to the number of characters in the string, it will return true. You need to add one because it is zero based.

55. Use PHP Echo like a Function Ive always thought that if you wanted to concatenate strings with echo, you needed to use periods. But you can actually treat echo like a function and use commas instead (it is also faster). Take a look at the following code:
<?php
$string1 = test-string1;
$string2 = test-string2;
$string3 = test-string3;

echo String #1: , $string1, <br />;
echo String #2: , $string2, <br />;
echo String #3: , $string3, <br />;
56. Use Single Quotes When Possible By using single quotes instead of double quotes, you save PHP from having to parse your string for variables. It not only is faster, but I find it more programmer-friendly because it is easier to find variables in your code. Also, when referencing an array that has a string index, always use single quotes. This prevents PHP from having to figure out exactly what you were trying to say.

 57. PHP Variable Variables There have been several cases when I needed to access a dynamic variable (where the variable name changed). You can do this easily in PHP by using what is called Variable Variables. Take a look at this example:
<?php
$var1 = nameOfVariable;
$nameOfVariable = This is the value I want!!!;

echo $$var1;
58. Use Arrays in Form Fields Not only can you create a form field that creates an element in an array (like name[firstname] ), but you can create dynamic arrays as well. This is especially useful in checkboxes, where the user could check multiple options. Take a look at this HTML:
<label><input type="checkbox" name="hobbies[]" value="Sports" 

/> Sports</label><br />
<label><input type="checkbox" name="hobbies[]" value="Hiking"

/> Hiking</label><br />
<label><input type="checkbox" name="hobbies[]" value="Swimming"

/> Swimming</label><br />
<label><input type="checkbox" name="hobbies[]" value="Swimming"

/> Watching Movies</label><
When the above fields are posted to a PHP page, each hobby is added to the hobbies array. You can then loop through that array and access each value that was checked.

 59. Rotate Random Quotes 

Using this simple, but effective code snippet, you can rotate random quotes or other pieces of information in a certain area on your site. You can adjust the code to show a random quote each time the page is refreshed, or you can control the quote being changed at random once during each day. Visitors will notice your changing content every day, and it will keep the page exciting and refreshing without the same, old boring text day in and day out. Insert this code into your document:
$quote = array(
1 => “Quote 1?,
2 => “Quote 2?,
3 => “Quote 3?,
4 => “Quote 4?,
5 => “Quote 5?,
);
srand ((double) microtime() * 1000000);
$randnum = rand(1,5);
echo”$quote[$randnum]“;
60.Notify Referrals 

Another cool little trick that you can use on your site is a script that displays the referrer that sent you to your site. For example, if a user came from Google to your site, they’ll be able to see a small section on your site that logs where they came from. The text from this code will appear as, “You reached this site via [referrer].”
$referer = $_SERVER[HTTP_REFERER];
echo “You reached this site via ” . $referer;
Hope you enjoy reading these 60 PHP tips and tricks.If you find this blog Interesting then you may subscribe to us to receive all future updates directly in your email.The Subscription Box is located just below this post.

Happy Reading!