为啥我的php脚本上传应该是图像的空白文件

Posted

技术标签:

【中文标题】为啥我的php脚本上传应该是图像的空白文件【英文标题】:why is my php script uploading blank files which should be images为什么我的php脚本上传应该是图像的空白文件 【发布时间】:2014-03-31 20:01:17 【问题描述】:

我使用的是直接从书中获得的 php 脚本,没有错误。它应该可以工作...当我使用我的 php 表单上传 jpg 文件时,该文件会进入我的上传文件夹,但它没有类型,它是一个空白文件。当我查看文件的属性时,它只是说文件。我正在使用的 php 脚本不使用 mime 类型来识别正在上传的文件类型。但是根据论坛,这门课程的其他学生似乎没有这个问题。会不会是windows 8?我上传文件夹的权限似乎很好。有什么想法吗?

这里是代码..

<?php # Script 19.2 - add_print.php
// This page allows the administrator to add a print (product).

require ('../mysqli_connect.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST')  // Handle the form.

    // Validate the incoming data...
    $errors = array();

    // Check for a print name:
    if (!empty($_POST['print_name'])) 
        $pn = trim($_POST['print_name']);
     else 
        $errors[] = 'Please enter the print\'s name!';
    

    // Check for an image:
    if (is_uploaded_file ($_FILES['image']['tmp_name'])) 

        // Create a temporary file name:
        $temp = '../../uploads/' . md5($_FILES['image']['name']);

        // Move the file over:
        if (move_uploaded_file($_FILES['image']['tmp_name'], $temp)) 

            echo '<p>The file has been uploaded!</p>';

            // Set the $i variable to the image's name:
            $i = $_FILES['image']['name'];
         else  // Couldn't move the file over.
            $errors[] = 'The file could not be moved.';
            $temp = $_FILES['image']['tmp_name'];
        

     else  // No uploaded file.
        $errors[] = 'No file was uploaded.';
        $temp = NULL;
    

    // Check for a size (not required):
    $s = (!empty($_POST['size'])) ? trim($_POST['size']) : NULL;

    // Check for a price:
    if (is_numeric($_POST['price']) && ($_POST['price'] > 0)) 
        $p = (float) $_POST['price'];
     else 
        $errors[] = 'Please enter the print\'s price!';
    

    // Check for a description (not required):
    $d = (!empty($_POST['description'])) ? trim($_POST['description']) : NULL;

    // Validate the artist...
    if ( isset($_POST['artist']) && filter_var($_POST['artist'], FILTER_VALIDATE_INT, array('min_range' => 1))  ) 
        $a = $_POST['artist'];
     else  // No artist selected.
        $errors[] = 'Please select the print\'s artist!';
    

    if (empty($errors))  // If everything's OK.

        // Add the print to the database:
        $q = 'INSERT INTO prints (artist_id, print_name, price, size, description, image_name) VALUES (?, ?, ?, ?, ?, ?)';
        $stmt = mysqli_prepare($dbc, $q);
        mysqli_stmt_bind_param($stmt, 'isdsss', $a, $pn, $p, $s, $d, $i);
        mysqli_stmt_execute($stmt);

        // Check the results...
        if (mysqli_stmt_affected_rows($stmt) == 1) 

            // Print a message:
            echo '<p>The print has been added.</p>';

            // Rename the image:
            $id = mysqli_stmt_insert_id($stmt); // Get the print ID.
            rename ($temp, "../../uploads/$id");

            // Clear $_POST:
            $_POST = array();

         else  // Error!
            echo '<p style="font-weight: bold; color: #C00">Your submission could not be processed due to a system error.</p>'; 
        

        mysqli_stmt_close($stmt);

     // End of $errors IF.

    // Delete the uploaded file if it still exists:
    if ( isset($temp) && file_exists ($temp) && is_file($temp) ) 
        unlink ($temp);
    

 // End of the submission IF.

// Check for any errors and print them:
if ( !empty($errors) && is_array($errors) ) 
    echo '<h1>Error!</h1>
    <p style="font-weight: bold; color: #C00">The following error(s) occurred:<br />';
    foreach ($errors as $msg) 
        echo " - $msg<br />\n";
    
    echo 'Please reselect the print image and try again.</p>';


// Display the form...
?>
<h1>Add a Print</h1>
<form enctype="multipart/form-data" action="add_print.php" method="post">

    <input type="hidden" name="MAX_FILE_SIZE" value="524288" />

    <fieldset><legend>Fill out the form to add a print to the catalog:</legend>

    <p><b>Print Name:</b> <input type="text" name="print_name" size="30" maxlength="60" value="<?php if (isset($_POST['print_name'])) echo htmlspecialchars($_POST['print_name']); ?>" /></p>

    <p><b>Image:</b> <input type="file" name="image" /></p>

    <p><b>Artist:</b> 
    <select name="artist"><option>Select One</option>
    <?php // Retrieve all the artists and add to the pull-down menu.
    $q = "SELECT artist_id, CONCAT_WS(' ', first_name, middle_name, last_name) FROM artists ORDER BY last_name, first_name ASC";        
    $r = mysqli_query ($dbc, $q);
    if (mysqli_num_rows($r) > 0) 
        while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) 
            echo "<option value=\"$row[0]\"";
            // Check for stickyness:
            if (isset($_POST['artist']) && ($_POST['artist'] == $row[0]) ) echo ' selected="selected"';
            echo ">$row[1]</option>\n";
        
     else 
        echo '<option>Please add a new artist first.</option>';
    
    mysqli_close($dbc); // Close the database connection.
    ?>
    </select></p>

    <p><b>Price:</b> <input type="text" name="price" size="10" maxlength="10" value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /> <small>Do not include the dollar sign or commas.</small></p>

    <p><b>Size:</b> <input type="text" name="size" size="30" maxlength="60" value="<?php if (isset($_POST['size'])) echo htmlspecialchars($_POST['size']); ?>" /> (optional)</p>

    <p><b>Description:</b> <textarea name="description" cols="40" rows="5"><?php if (isset($_POST['description'])) echo $_POST['description']; ?></textarea> (optional)</p>

    </fieldset>

    <div align="center"><input type="submit" name="submit" value="Submit" /></div>

</form>

【问题讨论】:

代码?错误?什么? 书上不代表对,请分享代码。 你放弃了这个帖子@user3286022 吗? 【参考方案1】:

您需要在文件路径中包含文件扩展名。一种方法是:

$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];

然后您只需要更改这行代码:

rename ($temp, "../../uploads/$id");

到:

rename ($temp, "../../uploads/$id.".".$extension");

如果您计划接受多种图像格式,那么将其文件扩展名连同它一起存储在数据库中总是值得的。这样,只需要一个简短的函数来生成文件名,同时仍然保持整数 id 用于搜索/链接到其他数据库的灵活性

【讨论】:

以上是关于为啥我的php脚本上传应该是图像的空白文件的主要内容,如果未能解决你的问题,请参考以下文章

PHP GD水印脚本产生空白水印

为啥我的 PHP 脚本在生成缩略图时会停止?

为啥文件只能部分上传?

为啥上传图片时收不到响应数据?

为啥在php中使用cropper js上传图像时需要不工作

为啥我的调整剪辑图像大小的脚本不起作用?