PHP 上传 - 只允许 jpg 文件

2022-01-09 00:00:00 file upload restriction php

这是我目前拥有的:

$file_name = $HTTP_POST_FILES['uid']['name'];
$user= 'FILENAME';
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$new_file_name=$user . '.' . $ext;
$path= "uploads/images/users/".$new_file_name;
if($ufile !=none)
{
  if(copy($HTTP_POST_FILES['uid']['tmp_name'], $path))
  {
  echo "Successful<BR/>"; 
  echo "File Name :".$new_file_name."<BR/>"; 
  echo "File Size :".$HTTP_POST_FILES['uid']['size']."<BR/>"; 
  echo "File Type :".$HTTP_POST_FILES['uid']['type']."<BR/>"; 
  }
  else
  {
  echo "Error";
  }
}

推荐答案

<?php

$allowedTypes = array('image/jpeg');

$fileType = $HTTP_POST_FILES['uid']['type'];

if(!in_array($fileType, $allowedTypes)) {
    // do whatever you need to say that
    // it is an invalid type eg:
    die('You may only upload jpeg images');
}

?> 

希望这会有所帮助.另外你为什么使用 HTTP_POST_FILES 而不是 $_FILES?您使用的是旧版本的 PHP 吗?

hope this helps. Also why are you using HTTP_POST_FILES instead of $_FILES? Are you working with an older version of PHP?

相关文章