Safely upload images with PHP

*文
Release: 2023-03-18 13:54:01
Original
1988 people have browsed it

How to upload images safely in PHP? This article mainly introduces the method of uploading pictures safely in PHP, which can detect the picture type and realize the function of safely judging pictures. I hope to be helpful.

The example in this article describes how to safely upload images in PHP. Share it with everyone for your reference. The specific analysis is as follows:

This code is used to upload pictures. It can detect whether the picture is safe according to the picture type. It is not a simple detection of the extension


<?php // upload.php
echo <<<_END
<html><head><title>PHP Form Upload</title></head><body>
<form method=&#39;post&#39; action=&#39;upload2.php&#39; enctype=&#39;multipart/form-data&#39;>
Select a JPG, GIF, PNG or TIF File:
<input type=&#39;file&#39; name=&#39;filename&#39; size=&#39;10&#39; />
<input type=&#39;submit&#39; value=&#39;Upload&#39; /></form>
_END;
if ($_FILES)
{
$name = $_FILES[&#39;filename&#39;][&#39;name&#39;];
switch($_FILES[&#39;filename&#39;][&#39;type&#39;])
{
case &#39;image/jpeg&#39;: $ext = &#39;jpg&#39;; break;
case &#39;image/gif&#39;: $ext = &#39;gif&#39;; break;
case &#39;image/png&#39;: $ext = &#39;png&#39;; break;
case &#39;image/tiff&#39;: $ext = &#39;tif&#39;; break;
default: $ext = &#39;&#39;; break;
}
if ($ext)
{
$n = "image.$ext";
move_uploaded_file($_FILES[&#39;filename&#39;][&#39;tmp_name&#39;], $n);
echo "Uploaded image &#39;$name&#39; as &#39;$n&#39;:<br />";
echo "<img src=&#39;$n&#39; />";
}
else echo "&#39;$name&#39; is not an accepted image file";
}
else echo "No image has been uploaded";
echo "</body></html>";
?>
Copy after login

Related recommendations:

php security filter function sample code

PHP secure email

PHP security detection code snippet (share)_PHP tutorial

The above is the detailed content of Safely upload images with PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template