简体   繁体   English

PHP上传-仅允许jpg文件

[英]PHP Upload - Allow only jpg files

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";
  }
}
<?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? 另外,为什么要使用HTTP_POST_FILES而不是$ _FILES? Are you working with an older version of PHP? 您是否正在使用旧版本的PHP?

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 试试这个代替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']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM