我能够很好地上传图片,但是当我将图片/ jpg,image / gif更改为application / msword和application / pdf时,它不起作用。这是我的代码。完全相同的代码适用于图像,但是对于上传文档和pdf,它会输出“无效文件”。这里发生了什么?我的文件只有大约30kb,远低于文件大小限制。
$allowedExts = array("pdf", "doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ( ( ($_FILES["file"]["type"] == "application/msword") || ($_FILES["file"]["type"] == "text/pdf") )
&& ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts))
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
}
else
{
echo "Invalid file."
}
答案 0 :(得分:35)
请勿使用['type']
参数来验证上传。该字段是用户提供的,可以简单地伪造,允许上传任何类型的文件。 ['name']
参数也是如此 - 这是用户提供的文件名。伪造也是微不足道的,因此用户发送nastyvirus.exe
并将其称为cutekittens.jpg
。
验证上传的正确方法是使用服务器端mime类型确定,例如,通过fileinfo,加上正确的上传成功检查,您不需要:
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
case 'image/jpeg':
case 'application/pdf'
case etc....
$ok = true;
default:
die("Unknown/not permitted file type");
}
move_uploaded_file(...);
您还使用用户提供的文件名作为move_uploaded_files的最终目标的一部分。将路径数据嵌入到该文件名中也是微不足道的,然后您可以盲目地使用它。这意味着恶意远程用户可以在您的服务器上的任何文件上涂鸦,他们知道路径,以及工厂新文件。
答案 1 :(得分:8)
请在代码中添加正确的mime-types - 至少包含以下内容:
.jpeg -> image/jpeg
.gif -> image/gif
.png -> image/png
可以找到mime类型列表here。
此外,简化代码的逻辑并报告错误编号,以帮助第一级支持追踪问题:
$allowedExts = array(
"pdf",
"doc",
"docx"
);
$allowedMimeTypes = array(
'application/msword',
'text/pdf',
'image/gif',
'image/jpeg',
'image/png'
);
$extension = end(explode(".", $_FILES["file"]["name"]));
if ( 20000 < $_FILES["file"]["size"] ) {
die( 'Please provide a smaller file [E/1].' );
}
if ( ! ( in_array($extension, $allowedExts ) ) ) {
die('Please provide another file type [E/2].');
}
if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) )
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
}
else
{
die('Please provide another file type [E/3].');
}
答案 2 :(得分:6)
$folder = "Resume/";
$temp = explode(".", $_FILES["uploaded"]["name"]);
$newfilename = round(microtime(true)).'.'. end($temp);
$db_path ="$folder".$newfilename ;
//remove the .
$listtype = array(
'.doc'=>'application/msword',
'.docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.rtf'=>'application/rtf',
'.pdf'=>'application/pdf');
if ( is_uploaded_file( $_FILES['uploaded']['tmp_name'] ) )
{
if($key = array_search($_FILES['uploaded']['type'],$listtype))
{if (move_uploaded_file($_FILES['uploaded'] ['tmp_name'],"$folder".$newfilename))
{
include('connection.php');
$sql ="INSERT INTO tb_upload
(filePath) VALUES ('$db_path')";
}
}
else
{
echo "File Type Should Be .Docx or .Pdf or .Rtf Or .Doc";
}
答案 3 :(得分:2)
你的一个条件是失败。检查文件的mime-type值 尝试使用application / pdf,而不是text / pdf。请参阅Proper MIME media type for PDF files
答案 4 :(得分:1)
您可以使用
$_FILES['filename']['error'];
如果发生任何类型的错误,则返回错误&#39;否则1,2,3,4或1如果完成
1:如果文件大小超过限制....您可以通过Google搜索找到其他选项
答案 5 :(得分:0)
<?php
//create table
/*
--
-- Database: `mydb`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_user_data`
--
CREATE TABLE `tbl_user_data` (
`attachment_id` int(11) NOT NULL,
`attachment` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_user_data`
--
ALTER TABLE `tbl_user_data`
ADD PRIMARY KEY (`attachment_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_user_data`
--
ALTER TABLE `tbl_user_data`
MODIFY `attachment_id` int(11) NOT NULL AUTO_INCREMENT;
*/
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$fileName=$_FILES["resume"]["name"];
$fileSize=$_FILES["resume"]["size"]/1024;
$fileType=$_FILES["resume"]["type"];
$fileTmpName=$_FILES["resume"]["tmp_name"];
$statusMsg = '';
$random=rand(1111,9999);
$newFileName=$random.$fileName;
//file upload path
$targetDir = "resumeUpload/";
$fileName = basename($_FILES["resume"]["name"]);
$targetFilePath = $targetDir . $newFileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(!empty($_FILES["resume"]["name"])) {
//allow certain file formats
//$allowTypes = array('jpg','png','jpeg','gif','pdf','docx','doc');
$allowTypes = array('pdf','docx','doc');
if(in_array($fileType, $allowTypes)){
//upload file to server
if(move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFilePath)){
$statusMsg = "The file ".$fileName. " has been uploaded.";
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only DOC,DOCX, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
//display status message
echo $statusMsg;
$sql="INSERT INTO `tbl_user_data` (`attachment_id`, `attachment`) VALUES
('NULL', '$newFileName')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "upload success";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<form id="frm_upload" action="" method="post" enctype="multipart/form-data">
Upload Resume:<input type="file" name="resume" id="resume">
<button type="submit" name="submit">Apply Now</button>
</form>
//output sample[![check here for sample output][1]][1]
答案 6 :(得分:-1)
对于application / msword和application / vnd.ms-excel,当我删除了大小限制时:
($_FILES["file"]["size"] < 20000)
......它运作正常。