【问题标题】:What is the difference between having/not having a '/' at the end when defining a directory?定义目录时末尾有/没有'/'有什么区别?
【发布时间】:2013-10-07 07:42:22
【问题描述】:

当引用 PHP 中的目录时,例如在下面的代码中。

index.php

if ($handle = opendir('/path/to/images/directory')) {

    while (false !== ($fileName = readdir($handle))) {

        ...

    }

    closedir($handle);
}

我们可以假设的设置如下。以下表示[directory],所有代码都在index.php 文件中,我们希望遍历的图像/文件在[images] 目录中。

-[css]
-[js]
-[inc]
-[images]
-index.php

特别是opendir('/path/to/images/directory')) { 行,引用该目录的最佳做法是什么?

最后应该有一个尾随/,因为它是一个目录还是不必要的? 应该是相对的吗?绝对? 我们可以改用SERVER_VARIABLES 吗?

【问题讨论】:

    标签: php coding-style directory standards opendir


    【解决方案1】:

    对于实际/绝对约定,我建议相对,但也许只是我。 它使您的代码更容易重新定位。

    然后,奇怪的是,我检查了 php 源代码,opendir 包含在各种 c 函数中,其中之一是

    php_check_open_basedir

     313                 while (ptr && *ptr) {
     314                         end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
     315                         if (end != NULL) {
     316                                 *end = '\0';
     317                                 end++;
     318                         }
     319 
     320                         if (php_check_specific_open_basedir(ptr, path TSRMLS_CC) == 0) {
     321                                 efree(pathbuf);
     322                                 return 0;
     323                         }
     324 
     325                         ptr = end;
     326                 }
    

    所以基本上它会在您的路径中循环,从一个 DEFAULT_DIR_SEPARATOR 跳转到另一个。 所以我想,越少越好。

    也在阅读您的代码,但也许只是我的口味: 使用 $dir."/".$filename 看起来比 $dir.$filename 好

    我猜无论如何在现实世界中没有区别。

    【讨论】:

    • 我的意思是一般来说,不仅仅是与我的代码有关。我的代码是为了举例。我想我要问的是,必须在定义目录时我总是在末尾有一个/
    • 是的,我的意思是一般。最后一个 / 并没有真正使用,差异很小,不明显。对于绝对或相对,我建议使用相对,以防有人将他的代码移动到其他服务器/位置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    相关资源
    最近更新 更多