Home > Backend Development > PHP Tutorial > How to upload images in PHP and check if they are safe

How to upload images in PHP and check if they are safe

墨辰丷
Release: 2023-03-31 18:00:01
Original
1992 people have browsed it

This article mainly introduces the method of uploading images safely in PHP. It can detect the image type and realize the function of safely judging the image. It is of great practical value. Friends in need can refer to it.

The examples in this article describe PHP security How to upload images. 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

Summary: The above is The entire content of this article is hoped to be helpful to everyone's study.

Related recommendations:

Principles and usage of encryption and decryption in php

Principles and usage of encryption and decryption in php

phpTwo commonly used methods to recursively delete folders

The above is the detailed content of How to upload images in PHP and check if they are safe. 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