2013-01-11 138 views
0

我在我的PHP文件中有以下代碼 - 初始化$ uploaded_files變量,然後調用getDirectory(也在下面列出)。PHP串聯,字符串長度= 0

現在,如果我做一個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); 
} 
+4

$ uploaded_files未在您的函數中聲明爲全局。 – crush

+0

噢,我做了 - 完全錯過了,謝謝你的幫助。只要Stackoverflow讓我接受你的答案。 – mattdonders

回答

4

你要麼需要添加:

global $uploaded_files; 

在你getDirectory函數的頂部,或

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

通過引用傳遞它。

您還可以使$ uploaded_files成爲getDirectory的返回值。

更多閱讀有關全局和安全性:http://php.net/manual/en/security.globals.php

2

PHP一無所知範圍。

當您在函數體內聲明一個變量時,它將不在該函數的範圍之外。

例如:

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

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

這正是試圖訪問變量$uploaded_files當您遇到的問題。