This article is covering some common activity that used to do while doing some work on the web using PHP based on my experience. I hope that it helps other developer to speed up development process.

PHP Array is Good

PHP array handling capabilities is exceptionally good. Looking at the manual, there’s more than enough function to nuke down arrays as we wanted. For example:

Swapping Values

$a = 10; $b = 20;
print "$a, $b";
// swap
list($a, $b) = array($b, $a);
print "$a, $b";

Trimming Array of String

$file = 'test.txt';
// trim each line
$lines = array_map('trim', file($file));

Gathering Information From User

Interaction between web application and user usually done by HTML forms or parameterized queries. The common way to gather information is using $_GET, $_POST, $_COOKIE global variables. Example:

// getting login information
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';

These are relatively simple but boring things to do. Also, we need to check either magic_quotes_gpc setting is turned on or not for security reason. So I usually create a simple function to get the values from GET/POST/COOKIE variables. I intentionally use a shortname, just to be simple


// array_map on array or scalar
function map($function, $var) {
  return is_array($var) ? array_map($function,$var) : $function($var);
}

// stripslashes on array or scalar
function strip($var) { 
  return map('stripslashes', $var); 
}

// retrieve $_POST values, safely
function post($thing) {
  if (isset($_POST[$thing])) {
    if (get_magic_quotes_gpc()) {
      return strip($_POST[$thing]);
    } else {
      return $_POST[$thing];
    }
  }
  return '';
}

// and this is how I use it:
$varnames = array( 'username', 'password', 'email', 'whatever' );
foreach($varnames as $var) {
  $$var = post($var);
}

// and then use the variable like when using PHP with register_globals ON, but with more
// safety

if (empty($username)) die('Username is empty');

// ...

Interact With MySQL

There’s no doubt that the most common database incorporated with PHP application is MySQL. So, I have some tricks to speedup development with MySQL.

Querying

Usually we do something common like:

if (false !== $rs = mysql_query("SELECT * FROM table", $conn)) {
  // consume
  while(false !== $row = mysql_fetch_assoc($rs)) {
    // do something with row
  }
}

Why using false !== operator? Well, since PHP is typeless, the result of mysql_query or mysql_fetch_xxx can be zero value. If we use the simple evaluation if ($row = mysql_fetch_xxx) and the row contain empty values, PHP could interpret a false condition.

Escaping Query Values

We could use some code anti-SQL injection instruction using mysql_real_escape_string. Since this function is so fucking long, I ended up creating a simple function for escaping that works on array or scalar.

// mysql escape on array or scalar
function mysql_escape($vars) { 
  if(phpversion() >= '4.3.0') {
    return array_map('mysql_real_escape_string', $vars);
  } else {
    return array_map('mysql_escape_string', $vars);
  }
}

// this is an example to use it
list($username, $password) = mysql_escape(array($username, $password));

Usually we use the mysql_real_escape_string with sprintf, for example:

$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
  mysql_real_escape_string($user),
  mysql_real_escape_string($password));

So I wrote a shortcut for these common action

function sqlprintf() {
  $args = func_get_args();
  if (count($args) < 2) {
    trigger_error('sqlprintf need two or more arguments', E_USER_ERROR);
    return false;
  }
  $sql = array_shift($args);
  $args = mysql_escape($args);
  array_unshift($args, $sql);
  return call_user_func_array('sprintf', $args);
}

Of course the PEAR::DB library is far much better than my hacks

Dumping Values Nicely

The print_r function is very useful for debugging values, but when viewed using browser it looks like crap, so I have a nice function for making it a little bit nicer.

// dump values with print_r, enclosed with pre tags
function dump($in) {
  echo "<pre>n", (is_array($in)) ? print_r($in) : $in, "n</pre>";
}

Outputting

While outputting to browser, we need to be careful with the values. All values must be HTML compliant, so I wrote a small helper function to do htmlspecialchars.

// htmlspecialchars on array or scalar
function html_escape($var) { 
  return map('htmlspecialchars', $var); 
}

I think thats the end of this part, I will continue this next time. Meanwhile you can download the entire functions here.