php - Move_Uploaded_File 导致 500 错误并且不会移动文件

标签 php mysql pdo

我正在尝试创建一个简单的上传表单,将相关详细信息放入数据库中。我的数据库方面工作正常,但是当我尝试将文件移动到相关目标路径时,它失败并出现错误 500。

我已经检查了以下内容:

  1. 错误日志,没有显示任何错误
  2. 文件夹存在
  3. 文件夹权限正确,可写

任何人都可以帮我解决导致错误的问题吗?

谢谢。

编辑:重复插入和更新,并使用 $_FILES 而不是 $photos_uploaded 进行更新

<?php
/**
 * Smarty plugin
 *
 * @package    Smarty
 * @subpackage PluginsFunction
 */

/**
 * Smarty {portfolioAdminUpload} plugin
 * Type:     function<br>
 * Name:     Display and provide function for image uploading to portfolio<br>
 * Purpose:  fetch file and move to relevant location.
 *
 * @author Kyle Holmes <kholmes at blacknovadesigns dot co dot uk>
 *
 * @param array                    $params   parameters
 * @param Smarty_Internal_Template $template template object
 *
 * @throws SmartyException
 * @return string|null if the assign parameter is passed, Smarty assigns the result to a template variable
 */
function smarty_function_portfolioAdminUpload()
{
global $db;
global $images_dir;

// initialization  
  $photo_upload_fields = '';  
  $counter = 1;  

  // If we want more fields, then use, preupload.php?number_of_fields=20  
  $number_of_fields = (isset($_GET['number_of_fields'])) ?  
    (int)($_GET['number_of_fields']) : 1;


  // Firstly Lets build the Category List  

  try {

                $stmt = $db->query('SELECT category_id,category_name FROM mod_portfolio_category') ;
                while($row = $stmt->fetch()){
                $photo_category_list .= '<option value="'.$row['category_id'].'">'.$row['category_name'].'</option>';
        }

  // Lets build the Image Uploading fields                      
                 while($counter <= $number_of_fields) { 
                        $photo_upload_fields .= '<tr><td>  
                              Photo'.$counter.'  
                              <input name="photo_filename"  
                            type="file" />  
                            </td></tr>  
                            <tr><td>  
                              Caption:  
                              <textarea name="photo_caption" cols="30"  
                                rows="1"></textarea>  
                            </td></tr>';
                                $counter++;  
                } 

            } catch(PDOException $e) {
                echo $e->getMessage();
            }

  // Final Output  
  echo '<html>   

<form enctype="multipart/form-data"  
  action="" method="post"  
  name="upload_form"> 
<div class="title">Lets upload Photos</div>    
  <table width="90%" border="0"  
    align="center" style="width: 90%;">  
    <tr><td>  
      Select Category  
      <select name="category">  
      '.$photo_category_list.'  
      </select>  
    </td></tr>  
    <! - Insert the image fields here --> ' 
    .$photo_upload_fields.' 
    <tr><td>  
      <input type="submit" name="submit"  
        value="Add Photos" />  
    </td></tr>  
  </table>  
</form>  
</body>  
</html>';  

//if form has been submitted process it
if(isset($_POST['submit'])){

// Fetch the image caption array 
    $photo_captions = $_POST['photo_caption'];

    $photo_category = $_POST['category'];

// Get File Type
    $file = $_FILES['photo_filename']['tmp_name'];
    $file_extension = image_type_to_mime_type(exif_imagetype($file));           


// Set Target Path for file upload 
    $target_path = '../' . $images_dir;

// Is the image really an image?
    $validextensions =  array(    
      'image/pjpeg' => 'jpg',   
      'image/jpeg' => 'jpg',   
      'image/gif' => 'gif',   
      'image/bmp' => 'bmp',   
      'image/x-png' => 'png',
      'image/png' => 'png'  
    ); 
// New Id generated             
    $new_id = $db->lastInsertId();      

// Generate a new name
    $simpleName = $_FILES["photo_filename"]['name'];   
    $filename = $new_id.rand().$_FILES["photo_filename"]['name'];

        try {

                //insert into database
                $stmt = $db->prepare('INSERT mod_portfolio_photos SET photo_filename = :photoFilename, photo_caption = :photoCaption, photo_category = :photoCategory') ;
                $stmt->execute(array(
                    ':photoFilename' => $filename,
                    ':photoCaption' => $photo_captions[$counter],
                    ':photoCategory' => $photo_category,
                ));

            } catch(PDOException $e) {
                echo $e->getMessage();
            }

    $target_path = $target_path . $filename;     // Set the target path with a new name of image.

    if (($_FILES["photo_filename"]["size"][$counter] < 100000000)     // Approx. 100kb files can be uploaded.
    && in_array($file_extension, $validextensions)) {       
    if (move_uploaded_file($_FILES["photo_filename"]['tmp_name'][$counter], $target_path) && is_writable($target_path)) {
// If file moved to uploads folder.
    echo '<span id="noerror">'.$simpleName.' uploaded successfully!.</span><br/><br/>';
    } 
    else {     
//  If File Was Not Moved.
    echo '<span id="error">'.$simpleName.' Failed to Upload - please try again!.</span><br/><br/>';
    }} 
    else {
//   If File Size And File Type Was Incorrect.
    echo '<span id="error">***Invalid file Size or Type***</span><br/><br/>';
    }

    $size = GetImageSize($target_path);    

// Wide Image    
    if($size[0] > $size[1])    
    {     
     $thumbnail_width = 100;     
     $thumbnail_height = (int)(100 * $size[1] / $size[0]);     
    }     

// Tall Image    
    else    
    {    
      $thumbnail_width = (int)(100 * $size[0] / $size[1]);    
      $thumbnail_height = 100;    
    }

    $gd_function_suffix = array(      
      'image/pjpeg' => 'JPEG',     
      'image/jpeg' => 'JPEG',     
      'image/gif' => 'GIF',     
      'image/bmp' => 'WBMP',     
      'image/x-png' => 'PNG'     
    );

// Get the Name Suffix on basis of the mime type     
    $function_suffix = $gd_function_suffix[$filetype];     

// Build Function name for ImageCreateFromSUFFIX     
    $function_to_read = 'ImageCreateFrom' . $function_suffix;     

// Build Function name for ImageSUFFIX     
    $function_to_write = 'Image' . $function_suffix;

// Read the source file     
    $source_handle = $function_to_read($target_path);     

    if ($source_handle) {     
// Let's create a blank image for the thumbnail     
      $destination_handle =     
        ImageCreateTrueColor($thumbnail_width, $thumbnail_height);     

// Now we resize it     
      ImageCopyResampled($destination_handle, $source_handle,     
        0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1]);     
    }     

// Let's save the thumbnail     
    $function_to_write($destination_handle, '..' . $images_dir . '/tb_' . $filename);

    }
    }

最佳答案

这里缺少一个斜杠:

// No slash at the end
$target_path = '../' . $images_dir;
....
// No slash between path and file
$target_path = $target_path . $filename;
                           ^^^^

应该是:

$target_path = $target_path .'/'. $filename;

关于php - Move_Uploaded_File 导致 500 错误并且不会移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37689552/

相关文章:

php - 调用未定义的方法 Illuminate\Routing\RouteFileRegistrar::get() - 从 Laravel 5.7 升级到 5.8 后出错

mysql - 为什么我的触发器不起作用?错误1064

mysql - 如何删除今天创建的所有记录?

php - 使用查询绑定(bind) Fuelphp

php - 在 Laravel 中一次更新多列值

php - PHP 是否有一种与 Django 模板语言几乎相似的模板语言?

php - MySQL 查询不只输出结果标题

MySQL:更新具有多个外键依赖关系的表

php - pdo 样式的数据表 - 将数据库连接注入(inject)导致错误的类

PHP PDO 正在破坏我的 $_POST 值?