PHP文件上传无法正常工作,如何解决?

时间:2019-02-14 21:08:17

标签: php html mysql

我正在网站上,此页面上有一个表单提交,包括文件上传,该表单从html到php到mysql都没有问题,但是文件上传似乎不想处理。

HTML(要提交的表单内):

Document: <input type="file" name="fileToUpload" required></br></br>

PHP(没有mysql启动):

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if($FileType != "doc" && $FileType != "docx" && $FileType != "pdf") {
    echo "Sorry, only DOC, DOCX, & PDF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

错误或者是文件类型,或者是底部。我在服务器上的任何地方都找不到php.ini。

感谢您的时间,我应该只制作一个php.ini吗?

编辑:这是print_r($ _ FILES);

enter image description here

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样?这未经测试,我只是拿出了您的文件类型检查并用数组替换了它。

<?php
$target_dir = "uploads/";
$allowed_types =array('doc','docx','pdf')
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$error = null;

// Get the file extension
$ext = pathinfo($target_file, PATHINFO_EXTENSION);

// Search the array for the allowed file type

if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if (in_array($ext, $allowed_types, false) != true) {
    $error = "Sorry, there was an error uploading your file.";
    return $error; // or use  exit;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been 
uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
    }
}
?>