PHP安全上传图片的方法

这篇文章主要介绍了PHP安全上传图片的方法,可检测图片类型实现安全判断图片的功能,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了PHP安全上传图片的方法。分享给大家供大家参考。具体分析如下:

这段代码用于上传图片,可以根据图片类型检测图片是否安全,不是简单的检测扩展名

  1. <?php // upload.php
  2. echo <<<_END
  3. <html><head><title>PHP Form Upload</title></head><body>
  4. <form method='post' action='upload2.php' enctype='multipart/form-data'>
  5. Select a JPG, GIF, PNG or TIF File:
  6. <input type='file' name='filename' size='10' />
  7. <input type='submit' value='Upload' /></form>
  8. _END;
  9. if ($_FILES)
  10. {
  11. $name = $_FILES['filename']['name'];
  12. switch($_FILES['filename']['type'])
  13. {
  14. case 'image/jpeg': $ext = 'jpg'; break;
  15. case 'image/gif': $ext = 'gif'; break;
  16. case 'image/png': $ext = 'png'; break;
  17. case 'image/tiff': $ext = 'tif'; break;
  18. default: $ext = ''; break;
  19. }
  20. if ($ext)
  21. {
  22. $n = "image.$ext";
  23. move_uploaded_file($_FILES['filename']['tmp_name'], $n);
  24. echo "Uploaded image '$name' as '$n':<br />";
  25. echo "<img src='$n' />";
  26. }
  27. else echo "'$name' is not an accepted image file";
  28. }
  29. else echo "No image has been uploaded";
  30. echo "</body></html>";
  31. ?>