Helios
05.08.2007, 02:46
Читал мануал по пхп с комментариями, наткнулся на один пост, который дал повод для размышления.
Автор использует этот скрипт для подгонки всех подгружаемых изображений:
<?php
class picture
{
var $save_dir; //where file will be saved
var $filename="spacer.gif"; //default file name initially
var $error_message=""; //string to be output if neccesary
var $width; //height of final image
var $height; //width of final image
function picture($save_directory, $file_array, $max_width, $max_height)
{
$this->save_dir = $save_directory;
$this->width = $max_width;
$this->height = $max_height;
//--change filename to time - make it unique
$temp_filename = $file_array['name'];
$ext = explode('.',$temp_filename);
$ext = $ext[count($ext)-1];
$temp_filename = time().".".$ext;
//--check that it's a jpeg or gif
if (preg_match('/^(gif|jpe?g)$/',$ext)) {
// resize in proportion
list($width_orig, $height_orig) = getimagesize($file_array['tmp_name']);
if ($this->width && ($width_orig < $height_orig)) {
$this->width = ($this->height / $height_orig) * $width_orig;
} else {
$this->height = ($this->width / $width_orig) * $height_orig;
}
$image_p = imagecreatetruecolor($this->width, $this->height);
//handle gifs and jpegs separately
if($ext=='gif'){
$image = imagecreatefromgif($file_array['tmp_name']);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $this->width, $this->height, $width_orig, $height_orig);
imagegif($image_p, $this->save_dir.$temp_filename, 80);
}
else
{
$image = imagecreatefromjpeg($file_array['tmp_name']);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $this->width, $this->height, $width_orig, $height_orig);
imagejpeg($image_p, $this->save_dir.$temp_filename, 80);
}
imagedestroy($image_p);
imagedestroy($image);
$this->filename=$temp_filename;
}else{
$this->error_message.="<br> file is not a jpeg or gif picture <br>";
}
}
}
Но чем не способ фильтровать полученные файлы?
Проблема только одна: для работы требуется поддержка GD в пхп, но в данный момент на большинстве хостингов она есть.
Вот набросанный за пару минут класс для фильтрации картинок:
<?php
/**
* Класс для проверки изображений
*
*/
class SecureImage
{
/**
* Картинка
* @var resource
*/
private $img = null;
/**
* Данные о картинке
* @var array
*/
private $data = null;
/**
* Тип изображения
* @var string
*/
private $type = null;
/**
* Конструктор класса
*
* @param string $s_patch Папка для сохранения картинки
*/
public function __construct($image_data)
{
$this->data = $image_data;
}
/**
* Деструктор класса
*/
public function __destruct()
{
if ($this->img)
{
imagedestroy($this->img); // освобождаем память
}
}
/**
* Проверка изображения
*
* @param array $image Массив с данными о загруженом файле из $_FILES
* @return boolean Результат проверки
*/
public function check()
{
$ext = explode('.',$this->data['name']);
$ext = trim(strtolower($ext[count($ext)-1]));
switch ($ext)
{
case 'gif':
$this->img = @imagecreatefromgif($image['tmp_name']);
$this->type = 'gif';
break;
case 'jpeg':
case 'jpg':
$this->img = @imagecreatefromjpeg($image['tmp_name']);
$this->type = 'jpg';
break;
case 'png':
$this->img = @imagecreatefrompng($image['tmp_name']);
$this->type = 'png';
break;
}
if ($this->img)
{
return true; // и правда, картинка
}
else
{
return false;// шелл батькович
}
}
/**
* Созранение изображения
*
* @param string $patch Путь для сохранения
* @return boolean Результат сохранения
*/
public function save($patch)
{
if (!$this->img) { return false; }
switch ($this->type)
{
case 'gif':
return imagegif($this->img, $patch); // на случай, если прав на запись в указанном месте нет
break;
case 'jpg':
return imagejpeg($this->img, $patch);
break;
case 'png':
return imagepng($this->img, $patch);
break;
default:
return false;
break;
}
}
/**
* Возвращает расширение для картинки
*/
public function getExtension()
{
return $this->type;
}
}
Вот пример его использования:
$img = new SecureImage($_FILES['some_image']);
if ($img->check())
{
// и правда, картинка - продолжаем.
$img->save('/path/to/images/my_image.' . $img->getExtension());
}
else
{
// shell, как он есть, или ошибка в картинке
}
Недостаток в том, что поддерживаются только gif, jpeg и png. Хотя аватарок в psd я нигде и не видел...
В общем, хочу узнать ваше мнение
Автор использует этот скрипт для подгонки всех подгружаемых изображений:
<?php
class picture
{
var $save_dir; //where file will be saved
var $filename="spacer.gif"; //default file name initially
var $error_message=""; //string to be output if neccesary
var $width; //height of final image
var $height; //width of final image
function picture($save_directory, $file_array, $max_width, $max_height)
{
$this->save_dir = $save_directory;
$this->width = $max_width;
$this->height = $max_height;
//--change filename to time - make it unique
$temp_filename = $file_array['name'];
$ext = explode('.',$temp_filename);
$ext = $ext[count($ext)-1];
$temp_filename = time().".".$ext;
//--check that it's a jpeg or gif
if (preg_match('/^(gif|jpe?g)$/',$ext)) {
// resize in proportion
list($width_orig, $height_orig) = getimagesize($file_array['tmp_name']);
if ($this->width && ($width_orig < $height_orig)) {
$this->width = ($this->height / $height_orig) * $width_orig;
} else {
$this->height = ($this->width / $width_orig) * $height_orig;
}
$image_p = imagecreatetruecolor($this->width, $this->height);
//handle gifs and jpegs separately
if($ext=='gif'){
$image = imagecreatefromgif($file_array['tmp_name']);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $this->width, $this->height, $width_orig, $height_orig);
imagegif($image_p, $this->save_dir.$temp_filename, 80);
}
else
{
$image = imagecreatefromjpeg($file_array['tmp_name']);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $this->width, $this->height, $width_orig, $height_orig);
imagejpeg($image_p, $this->save_dir.$temp_filename, 80);
}
imagedestroy($image_p);
imagedestroy($image);
$this->filename=$temp_filename;
}else{
$this->error_message.="<br> file is not a jpeg or gif picture <br>";
}
}
}
Но чем не способ фильтровать полученные файлы?
Проблема только одна: для работы требуется поддержка GD в пхп, но в данный момент на большинстве хостингов она есть.
Вот набросанный за пару минут класс для фильтрации картинок:
<?php
/**
* Класс для проверки изображений
*
*/
class SecureImage
{
/**
* Картинка
* @var resource
*/
private $img = null;
/**
* Данные о картинке
* @var array
*/
private $data = null;
/**
* Тип изображения
* @var string
*/
private $type = null;
/**
* Конструктор класса
*
* @param string $s_patch Папка для сохранения картинки
*/
public function __construct($image_data)
{
$this->data = $image_data;
}
/**
* Деструктор класса
*/
public function __destruct()
{
if ($this->img)
{
imagedestroy($this->img); // освобождаем память
}
}
/**
* Проверка изображения
*
* @param array $image Массив с данными о загруженом файле из $_FILES
* @return boolean Результат проверки
*/
public function check()
{
$ext = explode('.',$this->data['name']);
$ext = trim(strtolower($ext[count($ext)-1]));
switch ($ext)
{
case 'gif':
$this->img = @imagecreatefromgif($image['tmp_name']);
$this->type = 'gif';
break;
case 'jpeg':
case 'jpg':
$this->img = @imagecreatefromjpeg($image['tmp_name']);
$this->type = 'jpg';
break;
case 'png':
$this->img = @imagecreatefrompng($image['tmp_name']);
$this->type = 'png';
break;
}
if ($this->img)
{
return true; // и правда, картинка
}
else
{
return false;// шелл батькович
}
}
/**
* Созранение изображения
*
* @param string $patch Путь для сохранения
* @return boolean Результат сохранения
*/
public function save($patch)
{
if (!$this->img) { return false; }
switch ($this->type)
{
case 'gif':
return imagegif($this->img, $patch); // на случай, если прав на запись в указанном месте нет
break;
case 'jpg':
return imagejpeg($this->img, $patch);
break;
case 'png':
return imagepng($this->img, $patch);
break;
default:
return false;
break;
}
}
/**
* Возвращает расширение для картинки
*/
public function getExtension()
{
return $this->type;
}
}
Вот пример его использования:
$img = new SecureImage($_FILES['some_image']);
if ($img->check())
{
// и правда, картинка - продолжаем.
$img->save('/path/to/images/my_image.' . $img->getExtension());
}
else
{
// shell, как он есть, или ошибка в картинке
}
Недостаток в том, что поддерживаются только gif, jpeg и png. Хотя аватарок в psd я нигде и не видел...
В общем, хочу узнать ваше мнение