WebsiteCodingPractices

From Warwick Student Cinema
Revision as of 21:10, 17 January 2007 by 195.137.17.58 (talk) (Common standards on how to write php pages for the website)
Jump to: navigation, search

Common standards on how to write php pages for the website

Purpose

  • Make it easier for other people to edit your code
  • Ensure that pages are written securely
  • Encourage compatibility with future changes

Standard

  • Optional $page_title
  • Optional includes
    • Use include_once or require_once
    • Any includes that are not used on every page are to be included at the start of the page using them
  • All pages that require authentication are to start with

wscauth_requirepriv(PRIV); or
if(!wscauth_haspriv(PRIV)){return;}

  • All pages that are passed variables are to declare the variables after the authentication using

$var=$_REQUEST['var']; for url, post and cookie or
$var=$_GET['var']; for URL only
$var=$_POST['var']; for POST only
$var=$_COOKIE['var']; for cookie only

  • Optional check vars passed to the page for expected string format

eg. $pid=preg_match(/^[0-9]+/, $_GET['pid'],$match) ? $match[0] : false;
This will assign $pid to the value of pid in the url if it is a number.

  • Avoid nested or long if statements

eg. instead of if(COND){Do lots of code}
use if(!COND){return;}Do lots of code

  • Use functions to make the structure of a page clear
    • If the page performs lots of actions use a switch statment to call functions that perform the actions. Do not use lots of if statments throughout the page
    • If functions are used on more than one page, put them in an include
    • Where possible use existing functions even if it is slightly less efficient. This will make the website more reliable and have a negligable impact on performance.
  • All database queries are to be performed in functions specifically for that task
  • Database queries should use PEAR or string formatting functions

eg. $query=sprintf("SELECT * FROM table WHERE id='%d' AND string='%s'",
mysql_real_escape_string($id),
mysql_real_escape_string($string))