Archive for July, 2009

symfony: sfValidatorFile – invalid mime type (text/plain) for PNG images

On some systems sfValidatorFile may give you an error when trying to upoad PNG images. It says that it has invalid mime type – text/plain, though you have 'mime_types' = 'web_images' and other image formats work well.

It may be caused by wrong result from mime_content_type() function. To check if it’s your case create simple php script with just one line:

echo mime_content_type('path_to_your_png_image');

If it will give you text/plain then you have three options:

  1. Upgrade your PHP to 5.3.0, though I doubt it’s available for most *nix distributions at this time.
  2. Install PECL package Fileinfo.
  3. The easiest, modify form class.

In first two options sfValidatorFile will use finfo_open function prior to mime_content_type and it should give correct results for PNG image. However, upgrading PHP or installing PECL package isn’t always possible.

The simplest way to fix this bug is to apply small modifications to your form class, just reorder mime type guessers:

public function configure()
{
  $this->validatorSchema['image'] = new sfValidatorFile(array(
      'required'	=> false,
      'path'       => sfConfig::get('sf_upload_dir') . '/directory',
      'mime_types' => 'web_images'
    ));
  $this->validatorSchema['image']->setOption('mime_type_guessers', array(
    array($this->validatorSchema['image'], 'guessFromFileinfo'),
    array($this->validatorSchema['image'], 'guessFromFileBinary'),
    array($this->validatorSchema['image'], 'guessFromMimeContentType')
  ));
}

In this case validator will first try fileinfo (which should be available since PHP 5.3.0), then 'file -bi' which should work correctly on *nix platform and only if both failed it will use mime_content_type

Monday, July 27th, 2009