【问题标题】:move uploaded image into folder in php(move_uploaded_file() function)将上传的图像移动到 php 中的文件夹中(move_uploaded_file() 函数)
【发布时间】:2016-06-30 12:44:04
【问题描述】:

我在移动上传的文件时遇到问题。

<?php
$image_name = $_FILES['image']['name'] ;
$target_file = "../uploads/$image_name";
$targetFileForItem = "uploads/$image_name";

move_uploaded_file($_FILES['image']['tmp_name'], $target_file);


$sql = "INSERT INTO items (name , description,`price`, `country`, `release`, `condition`, `image`) 
        VALUES ('$name','$description','$price', '$country', '$date', '$condition', '$targetFileForItem')" ;

?>

变量$targetFileForItem 可以正常工作,并且可以很好地插入到我的数据库中,但是文件不会移动到$target_filevar 的文件夹中,即uploads。如您所见,我使用move_uploaded_file() 函数,但我不工作。有什么建议吗?

【问题讨论】:

  • 检查上传文件夹的权限
  • 整个代码是正确的
  • 绝对是权限问题和/或路径问题。
  • 我认为是权限问题,但我不知道如何解决
  • @ArevshatyanGegham 您使用的是 FTP 还是 localhost?如果它在 FTP 中,则右键单击该文件夹并将其权限更改为 755。

标签: php mysql database image move


【解决方案1】:

写信给debug

ini_set('display_errors',1);
error_reporting(E_ALL);

如果你的代码没问题,那么检查file permissions你可以使用这个

if (is_dir($target_file ) && is_writable($target_file )) {
    // do upload logic here
} else {
    echo 'Upload directory is not writable, or does not exist.';
}

is_writable Returns TRUE 如果文件名存在并且是writable。 filename 参数可能是一个目录名,允许您检查目录是否可写

更多信息请阅读http://php.net/manual/en/function.is-writable.php

【讨论】:

  • 好的,我试过了,发现is_dir($target_file) 不起作用。那我能做些什么呢?
  • 如果问题出在 is_dir() 中,则意味着不存在 direcort。然后检查你的文件路径
【解决方案2】:

检查您上传文件夹的权限,它必须是 775。如果您使用 FTP,请右键单击文件夹并将该文件夹的文件权限更改为 755。 如果是本地主机,那么它一定是路径或文件夹名称问题。

让你的代码像这样,这样你也可以找出错误。

<?php
$image_name = $_FILES['image']['name'] ;
$target_file = "../uploads/$image_name";
$targetFileForItem = "uploads/$image_name";

// if folder not exists than it will make folder.

if(!file_exists($target_file))
{
       mkdir($target_file, 0777, true);
}

if(move_uploaded_file($_FILES['image']['tmp_name'], $target_file))
{
      echo "file successfully uploaded";       
}
else
{
      echo "error in file upload";
}

?>

【讨论】:

  • 它开始移动图像,但也打印错误:“未定义变量:target_dir”。你能解释一下为什么我们需要$target_dirvar?
  • 我的错误 $target_dir 将是 $target_file。刚刚编辑了我的答案。
  • 当我将变量更改为$target_file 时,它出现了另一个错误,并且没有加载文件。错误:警告:move_uploaded_file():copy()函数的第二个参数不能是目录,警告:move_uploaded_file():无法移动,文件上传错误
猜你喜欢
  • 2021-06-21
  • 2014-11-09
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
相关资源
最近更新 更多