繁体   English   中英

检查目录是否存在,如果存在则继续,如果不存在则死亡

[英]Check if directory exist, if so continue, if not die

已经在这里解决了很多问题并且无法找到解决方案,所以......

我们创建了 PHP 练习供孩子们学习。 有时他们必须创建文件夹,这些文件夹可能会在许多步骤之后保持为空。 如果孩子们跳过创建文件夹,那么 PHP 会抛出令人讨厌的错误。 喜欢使用这样的代码显示自定义错误:

$file = 'mydir';
if(is_dir($file)) {
  die("<p>folder does not exist, please return and create as instructed...</p>");
} else {
  $file=fopen($file,"r");
}

所以要回顾一下。 函数检查目录是否存在,如果它继续脚本,它不会死并显示简单的消息,直到创建目录。 如果目录不存在我不希望 PHP 创建目录,孩子们必须学会遵循步骤:)

即使目录存在,我的代码也不会继续。 我究竟做错了什么?

您输入了错误的条件:以下是正确的条件。

$file = 'mydir';
if(is_dir($file))
{
    //DIRECTORY EXISTS
}
else
{
    //DIRECTORY DOES NOT EXIST
}

建议:当不需要双引号时使用单引号,它会按原样处理内容(即不影响它),这更简单,因为您不必使用“\\”作为控制字符(与"\\'" 的例外,如果你想在你的字符串中使用单引号)并且它使你的代码更有效率,因为 PHP 不必检查转义字符。

$location = 'mydir'; //Better call it location as directory =/= file.

if(is_dir($location))
{
    //$fout = fopen($file, 'rb'); //'rb' for binary mode, please use this instead.
    $fout = fopen($location . '/' . $file, 'rb'); //I assumed you wanted to write the file in the directory you were testing for.
}
else
{
    die('<p>folder does not exist, please return and create as instructed...</p>');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM