Optimize PHP Script – Best Tips

Optimize PHP Script – Best Tips

Optimize PHP Script – Best Tips

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.

[ad name=”In Post (LU)”]

  • 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.

[ad name=”In Post”]