繁体   English   中英

PHP串联,字符串长度= 0

[英]PHP Concatenation, String Length = 0

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

现在,如果我执行vardump($ uploaded_files),我会看到变量的内容,但是由于某种原因,当我调用<?php echo $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时遇到的问题。

暂无
暂无

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

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