我的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>";
}
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 );
}
您需要添加:
global $uploaded_files;
在getDirectory函数的顶部,或者
function getDirectory( &$uploaded_files, $path = '.', $level = 0 )
通过引用传递
你也可以让$uploaded_files作为getDirectory的返回值。
更多关于全局和安全的阅读:http://php.net/manual/en/security.globals.php
PHP不知道作用域。
当你在函数体中声明一个变量时,它在该函数的作用域之外将不可用。
例如:function add(){
$var = 'test';
}
var_dump($var); // undefined variable $var
这正是您在尝试访问变量$uploaded_files
时遇到的问题。