画像アップロード処理のセキュリティホールをふさぐ(CakePHP修行 #37)
- July 31st, 2007
- Posted in CakePHP関連
- Write comment
さてさてCakePHP修行。青い人に指摘されたセキュリティホールを防ぎます。
そのエントリーでも言及されている『T.Teradaの日記』も読みましたが、どうやら完璧な防ぎ方はないような・・・しかし青い人の提案どおり、できるところまでやってみます。
簡単にいうと「画像形式を調べて、画像変換をかましつつ、拡張子を変えてアップ」です。
画像形式を調べるのはgetimagesizeでいいのかな。JPG、GIF、PNG以外ははじくように設定し、次のようなコードにします。
// file upload
if (!empty($this->data['User']['pic']['name'])) {
// tmp file info
$tmp_file = $this->data['User']['pic']['tmp_name'];
$imginfo = getimagesize($tmp_file);
// file error handling (file size / JPG,GIF,PNG)
clearstatcache();
if (filesize($tmp_file)>300000 || ($imginfo[2] < 1 || $imginfo[2] > 3)) { $this->set('file_error',true); return false; }
// set file name
$upload_path = WWW_ROOT . "pics" . DS;
// set new width, height
$width_old = $imginfo[0];
$height_old = $imginfo[1];
$width_new = PIC_WIDTH;
$height_new = $height_old * ($width_new / $width_old);
// create new file
switch ($imginfo[2]) {
case 2: // jpeg
$filename = sprintf("%05d.jpg",$me['User']['id']);
$jpeg = imagecreatefromjpeg($tmp_file);
$jpeg_new = imagecreatetruecolor($width_new, $height_new);
imagecopyresampled($jpeg_new,$jpeg,0,0,0,0,$width_new,$height_new,$width_old,$height_old);
imagejpeg($jpeg_new, $upload_path . $filename, 100);
break;
case 1: // gif
$filename = sprintf("%05d.gif",$me['User']['id']);
$gif = imagecreatefromgif($tmp_file);
$gif_new = imagecreatetruecolor($width_new, $height_new);
imagecopyresampled($gif_new,$gif,0,0,0,0,$width_new,$height_new,$width_old,$height_old);
imagegif($gif_new, $upload_path . $filename, 100);
break;
case 3: // png
$filename = sprintf("%05d.png",$me['User']['id']);
$png = imagecreatefrompng($tmp_file);
$png_new = imagecreatetruecolor($width_new, $height_new);
imagecopyresampled($png_new,$png,0,0,0,0,$width_new,$height_new,$width_old,$height_old);
imagepng($png_new, $upload_path . $filename, 100);
break;
Default:
break;
}
$this->data['User']['pic'] = $filename;
} else {
$this->data['User']['pic'] = $me['User']['pic'];
}
これで一応大丈夫かな・・・拡張子も変えたし。さて、では次にいよいよお友達っぽいSNS処理に移ります。複雑なアソシエーションをつくらないといけないですね。
※ CakePHP修業は百式管理人がSNSっぽいものをCakePHPで作ろうとして挫折するまでの日記です。前回までのあらすじはこちらへ。


No comments yet.