0

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

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

有人可以帮忙吗?谢谢你。

/** 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>";
}

获取目录功能:

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 ); 
} 
4

2 回答 2

4

您要么需要添加:

global $uploaded_files;

在 getDirectory 函数的顶部,或

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

通过引用传递它。

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

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

于 2013-01-11T21:11:02.110 回答
2

PHP 对范围一无所知。

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

例如:

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

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

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

于 2013-01-11T21:13:29.750 回答