PHP上传 - 仅允许jpg文件

时间:2011-02-28 15:01:26

标签: php file upload restriction

这就是我目前所拥有的:

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

2 个答案:

答案 0 :(得分: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');
}

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

答案 1 :(得分:0)

永远不要相信这种情况。这是不安全的,可能会导致人们搞砸你的服务器。请尝试使用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;
}
?>

像这样使用它:

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