上传图片 PHP SQL

Uploading images PHP SQL

提问人:Yoeri Achterbergen 提问时间:8/19/2018 最后编辑:Khoa TruongDinhYoeri Achterbergen 更新时间:8/19/2018 访问量:726

问:

我的上传脚本有问题,希望有人能帮我解决这个问题。

<?php
if(isset($_POST['submit'])){
    // Include the database configuration file
    include_once 'dbconfig.php';

    // File upload configuration
    $targetDir = "uploads/";
    $allowTypes = array('jpg','png','jpeg','gif');


    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    if(!empty(array_filter($_FILES['files']['name']))){
        foreach($_FILES['files']['name'] as $key=>$val){
            // File upload path
            $fileName = basename($_FILES['files']['name'][$key]);
            $targetFilePath = $targetDir . $fileName;

            // Check whether file type is valid
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType, $allowTypes)){
                // Upload file to server
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
                    // Image db insert sql
                    $insertValuesSQL .= "('".$fileName."', NOW()),";

                }else{
                    $errorUpload .= $_FILES['files']['name'][$key].', ';

                }
            }else{
                $errorUploadType .= $_FILES['files']['name'][$key].', ';
            }
        }

        if(!empty($insertValuesSQL)){
            $insertValuesSQL = trim($insertValuesSQL,',');
            // Insert image file name into database
            $insert = $db->query("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL");
            if($insert){
                $errorUpload = !empty($errorUpload)?'Upload Error: '.$errorUpload:'';
                $errorUploadType = !empty($errorUploadType)?'File Type Error: '.$errorUploadType:'';
                $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
                $statusMsg = "Files are uploaded successfully.".$errorMsg;
            }else{
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }

    }else{
        $statusMsg = 'Please select a file to upload.';
    }

    // Display status message
    echo $statusMsg;

}
?>

<html>
<form action="" method="post" enctype="multipart/form-data">
    Select Image Files to Upload:
    <input type="file" name="files[]" multiple>

    <input class="upload-btn" type="submit" name="submit" value="UPLOAD">
</form>
</html>

如果我单击提交按钮并且没有选择图像,则代码会打印在屏幕上。Please select a file to upload.

如果我单击带有所选图像的提交按钮,则代码不显示任何内容,也不会上传任何图像。

怎么了?

php sql 文件上传

评论

0赞 Chris 8/19/2018
还要包含 HTML 中的 <form> 标记
0赞 ThS 8/19/2018
可能缺少 enctype 属性,因此,提供 HTML 代码会有所帮助。
0赞 RiggsFolly 8/19/2018
我们需要看到你的 HTML,包括<form>
0赞 Isaac 8/19/2018
您的表单没有操作?提交表格有什么用?
0赞 Yoeri Achterbergen 8/19/2018
操作在同一页面上。

答:

0赞 Rinsad Ahmed 8/19/2018 #1

似乎没有正确访问FILES数组。试试这个代码片段

if(!empty($_FILES)){
    foreach($_FILES as $key=>$val){
        // File upload path
        $fileName = basename($val['name']);
        $targetFilePath = $targetDir . $fileName;

        // Check whether file type is valid
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
        if(in_array($fileType, $allowTypes)){
            // Upload file to server
            if(move_uploaded_file($val["tmp_name"], $targetFilePath)){
                // Image db insert sql
                $insertValuesSQL .= "('".$fileName."', NOW()),";

            }else{
                $errorUpload .= $val['name'].', ';

            }
        }else{
            $errorUploadType .= $val['name'].', ';
        }
    }
 }
0赞 Khoa TruongDinh 8/19/2018 #2

以下是我对您的问题的说明:

1) 确保您的上传文件夹正确无误:

// File upload configuration
$targetDir = "uploads/";

在这种情况下,上传文件夹应与上传脚本处于同一级别

|--uploads
|
|--your_upload_script.php
|

2) 我删除了你的数据库脚本。它正在工作。

<!DOCTYPE html>
<html>
<head>
<!--    <script type="text/javascript" src="asset/js/jquery-3.2.1.min.js"></script>-->
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    Select Image Files to Upload:
    <input type="file" name="files[]" multiple>
    <input class="upload-btn" type="submit" name="submit" value="UPLOAD">
</form>
<script type="text/javascript">
</script>

<?php
if(isset($_POST['submit'])){
    // Include the database configuration file
    //include_once 'dbconfig.php';

    // File upload configuration
    $targetDir = "uploads/";
    $allowTypes = array('jpg','png','jpeg','gif');


    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    if(!empty(array_filter($_FILES['files']['name']))){
        foreach($_FILES['files']['name'] as $key=>$val){
            // File upload path
            $fileName = basename($_FILES['files']['name'][$key]);
            $targetFilePath = $targetDir . $fileName;

            // Check whether file type is valid
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType, $allowTypes)){
                // Upload file to server
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
                    // Image db insert sql
                    $insertValuesSQL .= "('".$fileName."', NOW()),";

                }else{
                    $errorUpload .= $_FILES['files']['name'][$key].', ';

                }
            }else{
                $errorUploadType .= $_FILES['files']['name'][$key].', ';
            }
        }

    }else{
        $statusMsg = 'Please select a file to upload.';
    }

    // Display status message
    echo $statusMsg;

}
?>
</body>
</html>

因此,请再次检查您的数据库脚本。
为了更好地跟踪错误,我们应该使用 try catch 语句来捕获异常

3)上传文件错误:

$_FILES["files"]["error"][$key]
#Check some cases:
   case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        throw new RuntimeException('Exceeded filesize limit.');
    default:
        throw new RuntimeException('Unknown errors.');

如果要上传多个文件,有如下示例: