PHP定义上传的目标文件夹



我使用以下PHP脚本将图像上传到服务器。事实上,它会将文件移动到我的脚本所在的同一文件夹(root(中。我想把它移到root/imageUploads文件夹中。谢谢你的提示!

$source = $_FILES["file-upload"]["tmp_name"];
$destination = $_FILES["file-upload"]["name"];
...
if ($error == "") {
if (!move_uploaded_file($source, $destination)) {
$error = "Error moving $source to $destination";
}
}

您需要检查目标文件夹是否存在。

$destination = $_SERVER['DOCUMENT_ROOT'] . '/imageUploads/'
if (! file_exists($destination)) { // if not exists
mkdir($destination, 0777, true); // create folder with read/write permission.
}

然后尝试移动文件

$filename = $_FILES["file-upload"]["name"];
move_uploaded_file($source, $destination . $filename);

所以现在你的目的地看起来是这样的:

some-file.ext

并且它的目录和执行它的文件相同

您需要将一些目录路径附加到当前目的地。例如:

$path = __DIR__ . '/../images/'; // Relative to current dir
$path = '/some/path/in/server/images'; // Absolute path. Start with / to mark as beginning from root dir

然后move_uploaded_file($source, $path . $destination)

应该提供目标文件夹的完整路径,以避免和移动上传文件的路径问题,我在下面为目标路径添加了三种变体

$uploadDirectory  = "uploads";
// Gives the full directory path of current php file
$currentPath = dirname(__FILE__); 
$source      = $_FILES["file-upload"]["tmp_name"];
// If uploads directory exist in current folder
// DIRECTORY_SEPARATOR gices the directory seperation "/" for linux and "" for windows
$destination = $currentPath.DIRECTORY_SEPARATOR.$uploadDirectory.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}
// If to current folder where php script exist
$destination = $currentPath.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}
// If uploads directory exist outside current folder
$destination = $currentPath.DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR.$uploadDirectory.DIRECTORY_SEPARATOR.$_FILES["file-upload"]["name"];
if (!move_uploaded_file($source, $destination)) {
echo $error = "Error moving $source to $destination";
}

最新更新