PHP kiểm tra xem tệp có phải là hình ảnh không

Trong hướng dẫn này, tôi sẽ chỉ cho bạn cách tạo tập lệnh xác thực hình ảnh. Bạn có thể chọn giữa 2 phương pháp xác thực. một cái sẽ xác minh xem tệp có thực sự là một hình ảnh hay không, bằng cách kiểm tra loại mime của tệp và cái còn lại kiểm tra phần mở rộng của tệp đã tải lên

Hãy bắt đầu tạo tập tin cấu hình

cấu hình. php

<?php
/* 
1 = Check if the file uploaded is actually an image no matter what extension it has
2 = The uploaded files must have a specific image extension
*/

$validation_type = 1;

if($validation_type == 1)
{
	$mime = array('image/gif' => 'gif',
                  'image/jpeg' => 'jpeg',
                  'image/png' => 'png',
                  'application/x-shockwave-flash' => 'swf',
                  'image/psd' => 'psd',
                  'image/bmp' => 'bmp',
                  'image/tiff' => 'tiff',
                  'image/tiff' => 'tiff',
                  'image/jp2' => 'jp2',
                  'image/iff' => 'iff',
                  'image/vnd.wap.wbmp' => 'bmp',
                  'image/xbm' => 'xbm',
                  'image/vnd.microsoft.icon' => 'ico');
}
else if($validation_type == 2) // Second choice? Set the extensions
{
	$image_extensions_allowed = array('jpg', 'jpeg', 'png', 'gif','bmp');
}

$upload_image_to_folder = 'images/';
?>

Bây giờ, hãy tạo biểu mẫu sẽ giúp chúng tôi tải tệp lên

<form enctype="multipart/form-data" action="validate_image_upload.php" method="POST">
    
<!-- MAX_FILE_SIZE must be set before the input element -->
<input type="hidden" name="MAX_FILE_SIZE" value="2048000" />

<!-- The name from the $_FILES array is determined by the input name -->
Select an Image: <input name="image_file" type="file" /> 
<input type="submit" value="Upload" />

</form>

PHP kiểm tra xem tệp có phải là hình ảnh không

Biểu mẫu của chúng tôi sẽ gửi dữ liệu tới validate_image_upload. php. Tại đây, tập lệnh sẽ kiểm tra loại xác thực. Nếu tệp được xác thực, người dùng sẽ thấy thông báo gửi thành công và tệp sẽ được chuyển vào thư mục hình ảnh đã chỉ định. Tệp đã tải lên không vượt qua được quy trình xác thực?

<?php
// Do not show notice errors
error_reporting (E_ALL ^ E_NOTICE);

if(!empty($_FILES)) // [START FILE UPLOADED]
{
include 'config.php';

$file = $_FILES['image_file'];

$file_name = $file['name'];

$error = ''; // Empty

// Get File Extension (if any)

$ext = strtolower(substr(strrchr($file_name, "."), 1));

Xác thực #1 – Kiểm tra xem tệp đã tải lên có phải là hình ảnh không. Điều này được thực hiện bằng hàm getimagesize()

kích thước mảng getimagesize ( string $filename [, array &$imageinfo] )

Hàm này trả về một mảng với thông tin cụ thể về tệp. Để trả về thông tin cụ thể như chiều rộng, chiều cao, loại mime, kênh, tệp được xác minh phải là một hình ảnh hợp lệ. Nếu $file_info trống thì tệp đã tải lên không phải là hình ảnh

Chúng tôi sẽ phát hiện loại mime của hình ảnh và chúng tôi sẽ sử dụng thông tin này để thêm phần mở rộng chính xác vào tệp

// Check for a correct extension. The image file hasn't an extension? Add one

   if($validation_type == 1)
   {
   $file_info = getimagesize($_FILES['image_file']['tmp_name']);

      if(empty($file_info)) // No Image?
      {
      $error .= "The uploaded file doesn't seem to be an image.";
      }
      else // An Image?
      {
      $file_mime = $file_info['mime'];

         if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
         {
         $extension = $ext;
         }
         else
         {
         $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
         }

         if(!$extension)
         {
         $extension = '';
         $file_name = str_replace('.', '', $file_name);
         }
	  }
   }

Xác thực #2 – Kiểm tra phần mở rộng của tệp đã tải lên

Chúng tôi sẽ sử dụng in_array() để xác định xem có thể tìm thấy phần mở rộng của tên tệp trong danh sách của chúng tôi với các phần mở rộng từ config. php. Nếu phần mở rộng không có trong danh sách, một thông báo lỗi sẽ được tạo thông báo cho người dùng rằng phần mở rộng của tệp đã tải lên không phải là phần mở rộng được chấp nhận

   else if($validation_type == 2)
   {
	  if(!in_array($ext, $image_extensions_allowed))
	  {
	  $exts = implode(', ',$image_extensions_allowed);
	  $error .= "You must upload a file with one of the following extensions: ".$exts;
	  }

	  $extension = $ext;
   }

Nếu không tìm thấy lỗi, hãy sao chép tệp vào thư mục đã chỉ định ($upload_image_to_folder) và hiển thị thông báo gửi thành công cho người dùng

   if($error == "") // No errors were found?
   {
   $new_file_name = strtolower($file_name);
   $new_file_name = str_replace(' ', '-', $new_file_name);
   $new_file_name = substr($new_file_name, 0, -strlen($ext));
   $new_file_name .= $extension;
   
   // File Name
   $move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);

   if($move_file)
	   {
	   $done = 'The image has been uploaded.';
	   }
   }
   else
   {
   @unlink($file['tmp_name']);
   }

   $file_uploaded = true;
} // [END FILE UPLOADED]
?>

Kiểm tra đầy đủ validate_image_upload. php có Biểu mẫu HTML và Trình xác thực

xác thực_hình ảnh_upload. php

<?php
// Do not show notice errors
error_reporting (E_ALL ^ E_NOTICE);

if(!empty($_FILES)) // [START FILE UPLOADED]
{
include 'config.php';

$file = $_FILES['image_file'];

$file_name = $file['name'];

$error = ''; // Empty

// Get File Extension (if any)

$ext = strtolower(substr(strrchr($file_name, "."), 1));

// Check for a correct extension. The image file hasn't an extension? Add one

   if($validation_type == 1)
   {
   $file_info = getimagesize($_FILES['image_file']['tmp_name']);

      if(empty($file_info)) // No Image?
      {
      $error .= "The uploaded file doesn't seem to be an image.";
      }
      else // An Image?
      {
      $file_mime = $file_info['mime'];

         if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
         {
         $extension = $ext;
         }
         else
         {
         $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
         }

         if(!$extension)
         {
         $extension = '';
         $file_name = str_replace('.', '', $file_name);
         }
	  }
   }
   else if($validation_type == 2)
   {
	  if(!in_array($ext, $image_extensions_allowed))
	  {
	  $exts = implode(', ',$image_extensions_allowed);
	  $error .= "You must upload a file with one of the following extensions: ".$exts;
	  }

	  $extension = $ext;
   }

   if($error == "") // No errors were found?
   {
   $new_file_name = strtolower($file_name);
   $new_file_name = str_replace(' ', '-', $new_file_name);
   $new_file_name = substr($new_file_name, 0, -strlen($ext));
   $new_file_name .= $extension;
   
   // File Name
   $move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);

   if($move_file)
	   {
	   $done = 'The image has been uploaded.';
	   }
   }
   else
   {
   @unlink($file['tmp_name']);
   }

   $file_uploaded = true;
} // [END FILE UPLOADED]
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title>Validate Image on Upload @ BitRepository.com</title>
  <meta name="Author" content="BitRepository.com">

  <meta name="Keywords" content="validate, image, upload, post, files">
  <meta name="Description" content="How to check if an uploaded file is an image">
 </head>

 <body>

<center>

 <?php
 if($file_uploaded)
 {
	 if($done)
	 {
	 echo '<font color="green">'.$done.'</font>';
	 }
	 else if($error)
	 {
	 echo '<font color="red">'.$error.'</font>';
	 }
	 echo '<br /><br />';
 }
 ?>

<form enctype="multipart/form-data" action="validate_image_upload.php" method="POST">
    
<!-- MAX_FILE_SIZE must be set before the input element -->
<input type="hidden" name="MAX_FILE_SIZE" value="2048000" />

<!-- The name from the $_FILES array is determined by the input name -->
Select an Image: <input name="image_file" type="file" /> <input type="submit" value="Upload" />

</form>

</center>

 </body>
</html>

LƯU Ý Vui lòng đảm bảo cấu hình. php nằm trong cùng thư mục với validate_image_upload. php và thư mục nơi tệp hình ảnh sẽ được di chuyển có thể ghi được

Làm cách nào để kiểm tra xem tệp có phải là hình ảnh trong PHP không?

php /* 1 = Kiểm tra xem tệp đã tải lên có thực sự là một hình ảnh hay không cho dù nó có phần mở rộng nào 2 = Các tệp đã tải lên phải có phần mở rộng hình ảnh cụ thể */ $validation_type = 1;

Làm cách nào để kiểm tra xem tệp là loại hình ảnh hay video trong PHP?

$mimeType = $request->images->getMimeType(); . if it was an image, this code will give you the image word in the $fileType and if it was a video this code will give you the video word in the $fileType, then you can check on it by the if conditions.

Làm cách nào để kiểm tra loại hình ảnh trong PHP?

PHP. Hàm imagetypes() .

Làm cách nào để kiểm tra hình ảnh đã tải lên hay chưa trong PHP?

Hàm is_uploaded_file() trong PHP là một hàm sẵn có dùng để kiểm tra xem tệp đã chỉ định có được tải lên qua HTTP POST hay không. Tên của tệp được gửi dưới dạng tham số cho hàm is_uploaded_file() và trả về True nếu tệp được tải lên qua HTTP POST.