【问题标题】:PHP file_exist not working correctly? [closed]PHP file_exist 无法正常工作? [关闭]
【发布时间】:2013-05-23 03:04:36
【问题描述】:

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

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

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

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 显示所有三个文件。

【问题讨论】:

  • 你在哪里使用file_exists(),正如你的标题所暗示的那样?
  • @ØHankyPankyØ 至少在链接中有一个,OP 提到...
  • 那么错误消息不是很清楚,您尝试上传此文件的文件夹不存在吗?
  • 能否添加上传功能的代码?
  • 请提供具体的代码,但很明显你的路径不正确,根据错误..

标签: php file-upload file-exists


【解决方案1】:

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

$thumb_path='notes/thumb';

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

【讨论】:

  • 使用单引号代替双引号可能也可以,但斜杠更好。
  • @Arjan 是的,最好将两者结合起来。
【解决方案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;
    }
}  

*注意:*上面的代码只是为了说明问题,不应该是 复制粘贴或用于生产。

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

$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;

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 2013-09-16
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    相关资源
    最近更新 更多