请有人帮忙吗?我有以下代码将文件上传到我的服务器并将其重命名为登录用户的任何人。例如,用户'coca-cola-lover'上传了一个jpeg - 该脚本也会重命名jpeg'coca-cola-lover.jpg'。
我的问题是我需要它将上传限制为jpegs - 并且还将文件大小限制为2mb。
请帮助 - 我试图找到整晚的解决方案。
提前致谢
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
答案 0 :(得分:3)
getimagesize告诉您文件的格式是什么
根据bgy的评论,您还应该强制文件扩展名为您想要的内容:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
绝不信任,也绝不使用客户提供的文件名。
答案 1 :(得分:3)
我建议exif_imagetype
:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
答案 2 :(得分:3)
您可以使用四者中的任何一个来检测文件的mimetype:
您还可以限制MimeType from the FileUpload element,但由于这是客户端代码,恶意用户可以轻松删除它(并且它在浏览器中也有错误):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
有关如何handle file uploads with PHP (including limiting file size), check the manual的更多信息。
答案 3 :(得分:1)
您可以通过normal mechanisms限制尺寸,但在上传后您需要使用fileinfo functions来确定文件类型。
答案 4 :(得分:1)
当前代码的一些建议
$_FILES
代替$HTTP_POST_FILES
。$extension = pathinfo($filename, PATHINFO_EXTENSION);
。is_uploaded_file
和move_uploaded_file
。$_FILES['file']['type']
- 用户可以修改。如果要将文件上载限制为以下要求:
image/jpeg
做类似的事情:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}