PHP - Secure Image Upload


SUBMITTED BY: Guest

DATE: May 23, 2013, 10:59 a.m.

FORMAT: PHP

SIZE: 1.8 kB

HITS: 1311

  1. <?php
  2. function isImg($data){
  3. $r = true;
  4. $notAllow = @explode('|','evel|base|encode|decode|print|close|hide|display|connect|select|order|src|link|charset|title|safe|mode|php|css|style|span|div|echo|play|stop|any|text|expression|behaviour|applet|link|style|frame|frameset');
  5. foreach($notAllow as $b){
  6. if(strpos($data, $b) !== false){
  7. $r = false;
  8. break;
  9. }
  10. }
  11. if($r){
  12. $im = @imagecreatefromstring($data);
  13. if(!$im)
  14. $r = false;
  15. }
  16. return $r;
  17. }
  18. if(isset($_POST))
  19. {
  20. if($_POST['do']=='upload')
  21. {
  22. $up['maxSize'] = 1000 * 1000; // just one mb :D in bytes;
  23. $up['types'] = array("image/jpeg", "image/png","image/gif"); // kb
  24. $up['path'] = "images/i".time()."_".rand(0000,99999).".png";
  25. $filename = $_FILES["file"]["name"];
  26. $filetype = $_FILES["file"]["type"];
  27. $filesize = $_FILES["file"]["size"];
  28. $name_tmp = $_FILES["file"]["tmp_name"];
  29. $data = file_get_contents($name_tmp);
  30. if(empty($filename))
  31. {
  32. echo 'please select file';
  33. }elseif(!in_array($filetype,$up['types']))
  34. {
  35. echo 'not allow file type';
  36. }elseif($filesize>$up['maxSize'])
  37. {
  38. echo 'file size to big';
  39. }elseif(!isImg($data))
  40. {
  41. echo 'please add true image ';
  42. }else{
  43. file_put_contents($up['path'], $data);
  44. echo 'create image done';
  45. echo '<img src="'. $up['path'].'"/>';
  46. }
  47. }
  48. }
  49. ?>
  50. <meta charset="utf-8" />
  51. <form action="index.php" method="post" enctype="multipart/form-data">
  52. <input type="file" name="file" />
  53. <input type="submit" value="Uplaoder"/>
  54. <input type="hidden" name="do" value="upload"/>
  55. </form>

comments powered by Disqus