PHP连接,字符串长度= 0

时间:2013-01-11 21:07:22

标签: php concatenation

我的PHP文件中有以下代码 - 初始化$ uploaded_files变量,然后调用getDirectory(也在下面列出)。

现在,如果我执行vardump($ uploaded_files),我会看到变量的内容,但出于某种原因,当我在HTML文件中调用<?php echo $uploaded_files; ?>时,我收到一条消息,指出“找不到文件” - 我是做错了吗?

有人可以协助吗?谢谢。

/** LIST UPLOADED FILES **/
$uploaded_files = "";

getDirectory( Settings::$uploadFolder );

// Check if the uploaded_files variable is empty
if(strlen($uploaded_files) == 0)
{
    $uploaded_files = "<li><em>No files found</em></li>";
}

getDirectory功能:

function getDirectory( $path = '.', $level = 0 )
{ 
    // Directories to ignore when listing output. Many hosts 
    // will deny PHP access to the cgi-bin. 
    $ignore = array( 'cgi-bin', '.', '..' ); 

    // Open the directory to the handle $dh 
    $dh = @opendir( $path ); 

    // Loop through the directory 
    while( false !== ( $file = readdir( $dh ) ) ){ 

        // Check that this file is not to be ignored 
        if( !in_array( $file, $ignore ) ){ 

            // Its a directory, so we need to keep reading down... 
            if( is_dir( "$path/$file" ) ){ 

                // We are now inside a directory
                // Re-call this same function but on a new directory. 
                // this is what makes function recursive. 


      getDirectory( "$path/$file", ($level+1) );   
        } 

        else { 
            // Just print out the filename 
            // echo "$file<br />"; 
            $singleSlashPath = str_replace("uploads//", "uploads/", $path);

            if ($path == "uploads/") {
                $filename = "$path$file";
            }
            else $filename = "$singleSlashPath/$file";

            $parts = explode("_", $file);
            $size = formatBytes(filesize($filename));
            $added = date("m/d/Y", $parts[0]);
            $origName = $parts[1];
            $filetype = getFileType(substr($file, strlen($file) - 4));
            $uploaded_files .= "<li class=\"$filetype\"><a href=\"$filename\">$origName</a> $size - $added</li>\n";
            // var_dump($uploaded_files);
        } 
    } 
} 

// Close the directory handle
closedir( $dh ); 
} 

2 个答案:

答案 0 :(得分:4)

您需要添加:

global $uploaded_files;

在getDirectory函数的顶部,或

function getDirectory( &$uploaded_files, $path = '.', $level = 0 )

通过引用传递它。

您还可以将$ uploaded_files设为getDirectory的返回值。

关于全局和安全性的更多阅读:http://php.net/manual/en/security.globals.php

答案 1 :(得分:2)

PHP对范围一无所知。

当您在函数体内声明变量时,它将不在所述函数范围之外可用。

例如:

function add(){
    $var = 'test';
}

var_dump($var); // undefined variable $var

这正是您在尝试访问变量$uploaded_files时遇到的问题。