handlename's blog

コード片など

Chrome からファイルをアップロードするとファイルのタイプがとれない

Windows の Chrome からファイルをアップロードすると、ファイルタイプがとれないみたい。
Chrome のバージョンは8.0。

Chrome からファイルをアップロードしたものをPHPで受けて、
$_FILES を var_dump したらこんな風になる。

array
  'file' => 
    array
      'name' => string 'hogehoge.zip' (length=12)
      'type' => string '' (length=0)
      'tmp_name' => string '/private/var/tmp/phpURHxui' (length=26)
      'error' => int 0
      'size' => int 1087323

$_FILES['file']['type'] が空文字列になる。

ちなみにFirefoxの場合。

array
  'file' => 
    array
      'name' => string 'hogehoge.zip' (length=12)
      'type' => string 'application/zip' (length=15)
      'tmp_name' => string '/private/var/tmp/phpURHxui' (length=26)
      'error' => int 0
      'size' => int 1087323

type を見てアップロードされたファイルの種類を判別していると痛い目に遭う。
symfonyではアップロードされたファイルそのものを見ているみたい。

symfony 1.4.7の sfValidatorFile より。

<?php
  // ...略...

  /**
   * Guess the file mime type with PECL Fileinfo extension
   *
   * @param  string $file  The absolute path of a file
   *
   * @return string The mime type of the file (null if not guessable)
   */
  protected function guessFromFileinfo($file)
  {
    if (!function_exists('finfo_open') || !is_readable($file))
    {
      return null;
    }

    if (!$finfo = new finfo(FILEINFO_MIME))
    {
      return null;
    }

    $type = $finfo->file($file);

    // remove charset (added as of PHP 5.3)
    if (false !== $pos = strpos($type, ';'))
    {
      $type = substr($type, 0, $pos);
    }

    return $type;
  }

  // ...略...