move_uploaded_file没有上传图片

时间:2015-03-23 16:04:08

标签: php mysql image-uploading

我正在尝试将文件上传到ima​​ges文件夹,并将目录路径插入mysql db。

这是我的HTML表格

<form enctype="multipart/form-data" method="post" action="newfacility.php">
        <fieldset>
            <legend>New Facility</legend>
            ...
            <label for="photo">Facility Photo:</label>                     
            <input type="file" id="facilityphoto" name="facilityphoto" /><br />
            <label for="province">Photo Description:</label>
            <input type="text" id="photodesc" name="photodesc" /><br />
            ....
            <input type="submit" value="Create" name="submit" />
        </fieldset>
    </form>

newfacility.php

require_once('../appvars.php');
require_once('upload_image.php');

//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);        
if (!$dbc) {
    die("Connection failed: " . mysqli_connect_error());
}

if (isset($_POST['submit'])) {
    // Grab the user data from the POST
    $facilityNumber = mysqli_real_escape_string($dbc, trim($_POST['facilitynumber']));
    ....
    ....

    //This is defined in appvars.php -- define('MM_UPLOADPATH', 'images/');

    //facility photo
    $facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
    $facilityPhotoDesc = mysqli_real_escape_string($dbc, trim($_POST['photodesc']));

    // check if the faciliy info already exists.
    if (!empty($facilityNumber) && !empty($facilityName) && !empty($facilityAddress) && !empty($facilityCity)) {

        $query = "SELECT * FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
                . "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";

        $data = mysqli_query($dbc, $query);
        //if the facility is unique insert the data into the database
        if (mysqli_num_rows($data) == 0) {
            //insert into facility table
            $query = "INSERT INTO facility (facility_id, account_id, facility_number, facility_name, facility_address,"
                    . " facility_city, facility_province, facility_postal_code, facility_photo, facility_roof_plan,"
                    . " facility_roof_size, facility_roof_size_inspected, facility_last_inspected_date, facility_inspected_by)"
                    . " VALUES (NULL, '$selectedAssocAccount', '$facilityNumber', '$facilityName', '$facilityAddress', "
                    . "'$facilityCity', '$facilityProvince', '$facilityPostalCode', '$facilityRoofSize', "
                    . "'$facilityRoofSizeInspected', '$facilityDayInspected', '$facilityInspectedBy')";
            mysqli_query($dbc, $query);

            //query used to get the facility_id of the facility we had just entered -- I haven't tested this yet.
            $getFacilityID = "SELECT facility_id FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
                . "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";

            $facilityID = mysqli_query($dbc, $getFacilityID);

            //insert into photo table
            $photoQuery = "INSERT INTO photo (photo_id, facility_id, photo, photo_desc)"
                        . "VALUES (NULL, $facilityID, $facilityPhoto, $facilityPhotoDesc)";
            mysqli_query($dbc, $photoQuery);

            // Confirm success with the user
            echo '<p>You have succesfully created a new facility. '
                . 'Please go back to the <a href="/admin.php">admin panel</a>.</p>';

            //testing to see if I can view the image
            echo '<img class="profile" src="' . MM_UPLOADPATH . $facilityPhoto . '"/>';

            //close db connection
            mysqli_close($dbc);
            exit();
        }

最后这里是upload_image.php

if(isset($_FILES["facilityphoto"])) { 
    // Check if file already exists
    if (file_exists($facilityPhoto)) {
        echo "Sorry, facility photo already exists.";
    }
    if($_FILES['facilityphoto']['error'] !==0) { 
        echo "Error uploading facility photo image.";
    } else {
        if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
            echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading the facility photo.";
       }
    }
}

所以我现在所遇到的错误是:echo "Sorry, there was an error uploading the facility photo.";

我不明白我在这里做错了什么导致图片没有上传到我的images/目录。

2 个答案:

答案 0 :(得分:1)

替换这些行:

if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)){
   echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}

用这些:

if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], 'images/'. $_FILES["facilityphoto"]["name"])){
   echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}

答案 1 :(得分:1)

我将提供一个仅解决文件上传问题的答案,所有数据库内容都是从答案条带化的,因为它不相关。

// returns true only if the file was written to $to, 
// the value of $status_msg will be a user friendly string
// representing the outcome.
function save_facility_photo($from, $to, &$status_msg) {
    // Check if file already exists
    if (file_exists($to)) {
        $status_msg = "Sorry, facility photo already exists.";
        return false;
    } 
    if (move_uploaded_file($from, $to)) {
        $status_msg = "The file ".basename($to)." has been uploaded.";
        return true;
    }
    $status_msg = "Sorry, there was an error uploading the facility photo.";
    return false;
}

if (isset($_POST['submit'])) {
    define('MM_UPLOADPATH', 'images/');

    $facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);

    if ($_FILES['facilityphoto']['error'] == UPLOAD_ERR_OK) {
        $status_msg = '';
        $from = $_FILES["facilityphoto"]["tmp_name"];
        $saved = save_facility_photo($from, $facilityPhoto, $status_msg);
    }
    else {
        // handle upload error
    }
    // continue with code
}

以下是我认为您的脚本中发生的事情的解释。

newfacility.php的顶部,调用require_once('upload_image.php');。现在让我们逐步upload_image.php 注意$facilityPhoto尚未定义

// this is very likely true
if(isset($_FILES["facilityphoto"])) { 
    // $facilityPhoto is undefined so file_exists(NULL) will return false
    if (file_exists($facilityPhoto)) { }
    // the image upload was probably successful, so we jump to the else branch
    if($_FILES['facilityphoto']['error'] !==0) { 

    } 
    else {
        // $facilityPhoto is undefined move_uploaded_file('p/a/t/h', NULL) 
        // will return false, so we jump to the else branch
        if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {

        } 
        else {
            // resulting in this error
            echo "Sorry, there was an error uploading the facility photo.";
       }
    }
}