PHP Upload - Allow only jpg files

心已入冬 提交于 2020-01-11 07:23:47

问题


This is what I currently have:

$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";
  }
}

回答1:


<?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');
}

?> 

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




回答2:


Never ever ever trust that happening. It's unsafe and could potentially lead to people screwing up with your server. Try this instead http://ar.php.net/imagecreatefromjpeg

<?php
function LoadJpeg($imgname){
    /* Attempt to open */
    $im = @imagecreatefromjpeg($imgname);

    if(!$im){ 
       throw new InvalidArgumentException("$imgname is not a JPEG image");
    }  

    return $im;
}
?>

Using it like so:

$uploadDir = "/path/to/uploads/directory";
$handle = LoadJpeg($_FILES['uid']['tmp_name']);
imagejpeg($handle, $uploadDir.DIRECTORY_SEPARATOR.$_FILES['uid']['name']);


来源:https://stackoverflow.com/questions/5143625/php-upload-allow-only-jpg-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!