Optimize PHP Script – Best Tips
By: Dzhuneyt Ahmed
Posted · 1 min read
Outdated: Several tips in this post reference practices from PHP 4/5 that are no longer relevant. Notably,
mysql_real_escape_string()was removed in PHP 7.0 (use prepared statements instead), andmd5()should not be used for password hashing (usepassword_hash()). Modern PHP versions have also made many of these micro-optimizations unnecessary.
Using PHP is great for dynamic website. However, more dynamic means more resource hungry. Here is a short list of tips you should follow to avoid putting the PHP interpreter in difficulty.
- Replace print() with echo().
- If you have a string, wrap it inside single quote (‘) instead of double quote (“).
- Use unset() to clean memory from unneeded large variables or arrays.
- Replace require_once() with require().
- When including or requiring a file, include the full path. This will save the time taken to resolve the OS path.
- Use str_replace() instead of preg_replace().
- Whenever possible, use “elseif” instead of case/switch.
- Avoid using error suppression with @.
- Always close the database connection when not needed anymore.
- When working with arrays, always use $row[‘id’] instead of $row[id].
- Avoid using PHP shortcode opening tags like ” Use a caching addon (eAccelerator or memcache) to avoid having the PHP interpreter compile the scripts every time.
- When increasing numerical variables like “$i++”, use “++$i” instead. Does the same job for less server time.
- Always clean user input with mysql_real_escape_string() (for MySQL data) and htmlspecialchars() (for data to be shown on the browser).
- Use md5() or another hashing function to store sensitive information like user passwords.
- ip2long() and long2ip() can be used to convert IP address from string to integer (for storing in database or other uses).
- When redirecting users to another page with header(“Location: “. $url); make sure to include exit; or die(); immediately afterwards to avoid script execution.

