0

我正在开发一个简单的 php 文件上传功能。

我用这个函数上传了三个文件:

这是我存储文件的目录结构:

ROOT-
    -notes-
        -demo-
             -demo_file1.jpg
        -main-
             -main_file1.jpg
        -thumb-
     -manage.php //file which handle uploading code

我正在调用这样的上传功能:

$demo_path="notes\demo";
list($demo_file_name,$error)=upload('demo_file',$demo_path,'pdf');
if($error!=""){
    echo 'error-demo'.$error;
    exit;
}
//uploading main file
$main_path="notes\main";
list($file_name,$error)=upload('main_file',$main_path,'pdf');
if($error!=""){
    echo 'error-main'.$error;
    exit;

}

//uploadnig thumbnail
$thumb_path="notes\thumb";
list($thumb_file_name,$error)=upload('file_thumb',$thumb_path,'jpg,gif,jpeg,png');
if($error!=""){
    echo 'error-thumb'.$error;
    exit;

}

此代码适用于演示文件和主文件,但拇指说错误

error-thumb 无法上传文件 {filename} :文件夹不存在。

你能帮我解决问题吗?

提前致谢。

注意:$_FILES 显示所有三个文件。

4

2 回答 2

6

使用正斜杠 ( /) 分隔目录名称:

$thumb_path='notes/thumb';

否则\t被解释为双引号中的制表符。

于 2013-05-28T08:46:48.200 回答
2

通常,直接定义文件路径被认为是不好的做法。您应该解析路径,如果目录不存在则创建目录,然后检查目录是否可读。例如:

function get_the_directory($dir) {
    $upload_dir = trim($dir);
    if(!file_exists($upload_dir)){  // Check if the directory exists
        $new_dir = @mkdir($upload_dir); // Create it if it doesn't 
    }else{
        $new_dir = true;  // Return true if it does
    }
    if ($new_dir) {  // If above is true
        $dir_len = strlen($upload_dir);  // Get dir length
        $last_slash = substr($upload_dir,$dir_len-1,1); // Define trailing slash
        if ($last_slash <> DIRECTORY_SEPARATOR) {  // Add trailing slash if one is not present
            $upload_dir = $upload_dir . DIRECTORY_SEPARATOR;  
        } else {
            $upload_dir = $upload_dir;
        }
        $handle = @opendir($upload_dir);
        if ($handle) { //  Check if dir is readable by the PHP user
            $upload_dir = $upload_dir;
            closedir($handle);
            return $upload_dir;
        } else {
            return false;
        }
    } else {
        return false;
    }
}  

*注意: *以上代码仅用于说明这一点,请勿复制粘贴或在生产中使用。

解析路径,检查它是否存在,如果不存在则创建一个新目录,如果不存在则添加尾部斜杠应该是完全消除服务器故障、捕获错误并返回 false 的方法。开发使用只需将绝对路径传递给您的函数:

$dir = '';
if(!your_dir_function('/path/to/upload/dir/')){
    $dir = 'Sorry, directory could not be created';
}else{
    $dir = your_dir_function('/path/to/upload/dir/');
}

// Write upload logic here

echo $dir;

希望这可以帮助

于 2013-05-28T09:01:10.663 回答