提交表单时 _POST 或 _FILES 为空

Either _POST or _FILES is empty when submitting form

我正在尝试使用 php 和 html 将一个简单的图像文件上传到我的项目,但是当我提交表单时,_FILE 方法为空或 _POST 方法为空。我的代码从未通过 if 语句检查所有字段是否为空,因为我收到错误:“所有字段都是必填的,请填写所有字段。”

这是我的 CRUD.php 文件,直到出现错误消息:

// Include and initialize database class
require_once(ROOT_DIR . '/Classes/database.class.php');
$imageDB = new DB();

$tblName = 'image';

 // The folder where the images will be stored
 $uploadDir = CONTENT_PATH . '/';

 // Allow file formats
 $allowTypes = array('jpg', 'png', 'jpeg', 'gif');

 // Set default redirect url
 $redirectURL = PUBLIC_PATH . '/manageUploads.php';

 $statusMsg = '';
 $sessData = array();
 $statusType = 'danger';
 
// Check if user has uploaded new image
if (isset($_POST['imgSubmit'])) {
    //Set redirect url
    $redirectURL = PUBLIC_PATH . '/addEdit.php';

    //Get submitted data and clean it from injections
    $id = $_POST['id'];
    $image = $_FILES['image'];
    echo $image['name'];
    
    //Store title variable without any html or php tags and trims whitespace from beginning and end
    $title = strip_tags(trim($_POST['title']));  
    
    // Validate user tags are separated by comma or space and contain only alphanumeric or space/comma input 
    $regex = '/^[ ,]*[a-zA-Z0-9]+(?:[ ,]+[a-zA-Z0-9]+){0,5}[ ,]*$/';
    if (preg_match($regex, $_POST['tags']) == 0) {
        exit('Tags are not valid!'); 
    }
    // Makes all tags lower case
    $tag_input = strtolower($_POST['tags']); 

    // Clean up multiple commas or whitespaces
    $clean_tag_input = preg_replace('/[\s,]+/', ' ', $tag_input);

    // Replaces spaces with commas
    $comma_tags = str_replace(' ', ',', $clean_tag_input);

    // Submitted user data
    $imgData = array('title' => $title,'tags' => $comma_tags);
    
    // Store submitted data into session
    $sessData['postData'] = $imgData;
    $sessData['postData']['id'] = $id;

    // ID query string
    $idStr = !empty($id)?'?id='.$id:'';

    // If the data is not empty
    if ((!empty($image['name']) && !empty($title) && !empty($comma_tags)) || (!empty($id) && !empty($title) && !empty($comma_tags))) {
        echo $title;
        if(!empty($image)) {
            $filename = basename($image['name']);

            // Get file extension in lower case
            $fileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            echo $fileType;

            // Generate a unique name for the image to prevent throwing exists error
            $unique_image_name = rand(10000, 990000) . '_' . time() . '.' . $fileType;

            // The path of the new uploaded image
            $targetFilePath = $uploadDir . $unique_image_name;
            echo $targetFilePath;

            if (in_array($fileType, $allowTypes)) {
                
                // Check to make sure the image is valid
                if (!empty($image['tmp_name']) && getimagesize($image['tmp_name'])) {

                    if (file_exists($unique_image_name)) {
                        $statusMsg = 'Image already exists, please choose another or rename that image.';

                    } else if ($image['size'] > 500000) {
                        $statusMsg = 'Image file size too large, please choose an image less than 500kb.';
                    } else {
                        // Everything checks out now we can move the uploaded image
                        if (move_uploaded_file($image['tmp_name'], $targetFilePath)){
                            $imgData['filename'] = $unique_image_name;
                            $imgData['username'] = $_SESSION['username'];
                        } else {
                            $statusMsg = 'Sorry, there was an error uploading your file.';
                        }
                    }
                }
                } else {
                        $statusMsg = 'Image file is empty or corrupt.';
                }
            } else {
                $statusMsg = 'Sorry, only JPG, JPEG, PNG && GIF files are allowed to be uploaded.';
            }
        } else {
            $statusMsg = 'Sorry something went wrong.';
        }

        if (!empty($id)) {
            // Previous filename
            $conditions['where'] = array('id' => $_GET['imageID'],);
            $conditions['return_type'] = 'single';
            $prevData = $imageDB->getRows('image', $conditions);

            // Update data
            $condition = array('id' => $id);
            $update = $imageDB->update($tblName, $imgData, $condition);

            if($update) {
                //Remove old file from server
                if (!empty($imgData['filename'])) {
                    @unlink($uploadDir . $prevData['filename']);
                }
                $statusType = 'success';
                $statusMsg = 'Image data has been updated successfully.';
                $sessData['postData'] = '';

                $redirectURL = PUBLIC_PATH . '/manageUploads.php';
            } else {
                $statusMsg = 'Some problem occurred, please try again.';
                //Set redirect url
                $redirectURL .= $idStr;
            }
        } elseif (!empty($imgData['filename'])) {
            // Insert data
            $insert = $imageDB->insert($tblName, $imgData);

            if ($insert) {
                $statusType = 'success';
                $statusMsg = 'Image has been uploaded successfully.';
                $sessData['postData'] = '';

                $redirectURL = PUBLIC_PATH . '/manageUploads.php';
            } else {
                $statusMsg = 'Some problem occurred, please try again.';
            }
        
    } else {
        $statusMsg = 'All fields are mandatory, please fill all the fields.';
    }

这是我的 addEdit.php 格式的文件:

require_once(ROOT_DIR . '/Templates/header.php');

$postData = $imgData = array();
$newViewkey = uniqid();

// Get image data
if (!empty($_GET['imageID'])) {
    //include and initialize DB class
    require_once(ROOT_DIR . '/Classes/database.class.php');
    $addEditDB = new DB();

    $conditions['where'] = array('id' => $_GET['imageID'],);

    $conditions['return_type'] = 'single';
    $imgData = $addEditDB->getRows('image', $conditions);
}

// Pre-filled data
$imgData = !empty($postData)?$postData:$imgData;

// Define action
$actionLabel = !empty($_GET['imageID'])?'Edit':'Add';


head('Upload Image', $_SESSION['username'])
?>
<!-- Display status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="message">
    <?php echo $statusMsg; ?>
</div>
<?php } ?>

<div class="upload-form">
    <h1>Upload Image</h1>

    <form action="<?php echo IMAGE_UTIL_PATH;?>/crud.php" method="POST" enctype="multipart/form-data">
        <label for="title">Title</label>
            <input 
                type="text" name="title" id="title" 
                placeholder="Type image title here." 
                value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" required>

        <?php if (!empty($imgData['tags'])) {
            $tagsSpaces = preg_replace('/,/', ', ', trim($imgData['tags']));
        } ?>
        <label for="tags">Tags</label>
            <textarea name="tags" id="tags" placeholder="Enter at least 1 tag describing the image separated by a space ' ' or a ','."  required><?php echo !empty($imgData['tags'])?$tagsSpaces:''; ?></textarea>
        
        <input type="file" name="image" id="image" value="<?php echo !empty($imgData['filename'])?$imgData['filename']:''; ?>" required>

        <input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">

        <input type="hidden" name="modified" value="<?php echo !empty($imgData['id'])?date('Y/m/d h:m:s'):''; ?>">

        <input type="hidden" name="viewkey" value="<?php echo !empty($imgData['viewkey'])?$imgData['viewkey']:$newViewkey;?>">
        
        <?php if (!empty($imgData['filename'])) { ?> 
        <div>
            <img src="<?php echo !empty($imgData['filename'])?$imgData['filename']:'';?>" height=75 width=auto >
        </div>
    <?php } ?>

        <input type="submit" value="Upload" name="imgSubmit">
    </form>
    <div class="message">
        <a href="manageUploads.php">Back to Manage Uploads</a>
    </div>
    
</div>

<?php require_once(ROOT_DIR . '/Templates/footer.php')?>

最后这是我的 config.php 文件,其中包含所有路径定义:

/*
Set include path to include files outside root directory
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\xampp\htdocs\Shape_Search\resources');

/*
Error reporting
*/
ini_set("display_errors", "true");
error_reporting(E_ALL|E_STRICT);

/*
Create constants for heavily used paths relative to config file location
*/
defined('ROOT_DIR')
    or define('ROOT_DIR', dirname(__FILE__));

defined('SRC_DIR')
    or define('SRC_DIR', dirname(dirname(__FILE__)) . '\src');

defined('PUBLIC_PATH')
    or define('PUBLIC_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html');

defined('CONTENT_PATH')
    or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');

defined('LAYOUT_PATH')
    or define('LAYOUT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/layout');

defined('CSS_PATH')
    or define('CSS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/css');

defined('JS_PATH')
    or define('JS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/js');

defined('LIBRARY_PATH')
    or define('LIBRARY_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/resources/Library');

defined('CLASSES_PATH')
    or define('CLASSES_PATH', realpath(dirname(__FILE__)) . '/Classes');

defined('TEMPLATES_PATH')
    or define('TEMPLATES_PATH', realpath(dirname(__FILE__)) . "\Templates");

defined('IMAGE_UTIL_PATH')
    or define('IMAGE_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/ImageUtilities');

defined('RATING_UTIL_PATH')
    or define('RATING_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/RatingUtilities');

defined('USER_UTIL_PATH')
    or define('USER_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/UserUtilities');

?>

这是我的 php 错误日志:

[10-Feb-2022 13:52:06 Europe/Berlin] PHP 警告:move_uploaded_file(/Shape_Search/public_html/img/content/973439_1644497526.jpg):无法打开流:否C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php 第 116 行中的此类文件或目录 [2022 年 2 月 10 日 13:52:06 Europe/Berlin] PHP 警告:move_uploaded_file():无法将“C:\xampp\tmp\phpCCA.tmp”移动到“/Shape_Search/public_html/img/content/973439_1644497526.jpg" 在 C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php 第 116 行

这是目录与路径的问题。

 // The folder where the images will be stored
 $uploadDir = CONTENT_PATH . '/';

应更正为:

 // The folder where the images will be stored
 $uploadDir = CONTENT_DIR . '/';

其中全局变量CONTENT_PATH和CONTENT_DIR是:

defined('CONTENT_PATH')
    or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');

defined('CONTENT_DIR')
    or define('CONTENT_DIR', dirname(dirname(__FILE__)) . '/public_html/img/content');