WebIT.ca

Web development for online publishing

Posts Tagged ‘php’

Uploaded Excel mime type

Thursday, November 5th, 2009

I’ve been strugling to find the reason behind a malfunctioning Excel upload feature. The problem was that some times, the file would not have the application/vnd.ms-excel mime type. This was a bit of an issue, it was required for invaliding the type of the file.

By luck, a coworker discovered that the Excel file would return a different mime type if the Excel file was open in Excel when it was uploaded. Under these conditions, the mime type is application/octet-stream. In other words, when uploading an open Excel doc, Internet Explorer would have trouble identifying the file type and send along the generic mime-type application/octet-stream.

Bellow is a quick fix that should take care of future problems:

if (   $_FILES['excel_file']['type'] == 'application/vnd.ms-excel'
    || preg_match('/\\.xls$/', $_FILES['excel_file']['name']) ) {
    // continue working on the uploaded file...
}

PHP isset()

Sunday, September 20th, 2009

The PHP function isset() is often used to determine the presence of a variable. When the variable is not defined, false is returned. Using isset() is also an easy way to determine whether an array has a given key.

$assoc = array('key' => 'value');
echo isset($assoc['key']) ? 'true' : 'false';
// true
echo isset($assoc['missing']) ? 'true' : 'false';
// false

There is a catch: isset() called on a null variable will return false.

$var = null;
echo isset($var) ? 'true' : 'false';
// false
 
$array = array('key' => null);
echo isset($array['key']) ? 'true' : 'false';
// false

For checking the presence of a key in an array, use the PHP function array_key_exists() instead.

echo array_key_exists('key', $array) ? 'true' : 'false';
// true
 
function has_empty($key, &$array) {
    return array_key_exists($key, $array) && !$array[$key];
}
echo has_empty('key', $array) ? 'true' : 'false';
// true

To determine the presence of a null variable, a custom function is required.

function isvar($var) {
    return isset($var) || @is_null($var);
}
$null = null;
echo isvar($null) ? 'true' : 'false';
// true