PHP:文件上传脚本和move_upload_file

时间:2015-11-11 16:51:43

标签: php file-upload php-5.6

我在PHP中创建一个简单的文件上传脚本来上传XML文件(它实际上是一个WordPress插件),我怀疑我在将文件从temp文件夹传递到我指定的文件夹时遇到问题。完整的脚本如下所示,脚本实际运行并成功,echo语句"The file ". basename( $_FILES["upload"]["name"]). " has been uploaded.";显示器。但是,XML文件永远不会出现在目标目录中。有趣的是,如果我尝试两次上传相同的文件,则if语句返回指示文件已存在的情况返回true。抱歉,如果这是一个明显的问题,我对PHP很新。

$target_dir = "/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files";
 (upload) from the form
$target_file = $target_dir . basename($_FILES["upload"]["name"]);
$success = 1;
$type = pathinfo($target_file,PATHINFO_EXTENSION);

if((!empty($_FILES["upload"]))) 
{
    if (file_exists($target_file)) {
        echo "Sorry, file already exists, please archive or remove existing xml files before uploading a new file.";
        $success = 0;
    }
        if ($_FILES["upload"]["size"] > 500000) {
            echo "Sorry, your file is too large.";
            $success = 0;
        }
            if($type != "xml") 
            {
                echo "Only XML file types are allowed";
                $success = 0;
            }
                if ($success == 0) 
                {
                    echo "Error uploading.";
                } 
                    else 
                    {
                        if (move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)) 
                        {
                            echo "The file ". basename( $_FILES["upload"]["name"]). " has been uploaded.";
                        } 
                            else 
                            {
                                echo "Sorry, there was an error uploading your file.";
                            }       
                     }
    }
    else
    {
    echo "Please upload a file!";
    }

1 个答案:

答案 0 :(得分:0)

问题在$ target_dir路径中。根目录路径错误。使用$ _SERVER ['DOCUMENT_ROOT']。

更改此行

$target_dir = "/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files";

$target_dir = $_SERVER['DOCUMENT_ROOT']."/wordpress/wp-content/uploads/wpallimport/files";

这样所有文件都会上传到“files”目录。

现在文件被上传到错误的目录中。这就是为什么你不能在文件目录中看到它们。

在Linux Server(Ubuntu,CentOS)中,用户目录不是根目录。它存在于“home”目录下。但根据LINUX的味道和版本,它可能会有所不同。

echo $_SERVER['DOCUMENT_ROOT'];

这将帮助您找到您的Root directoy。