簡體   English   中英

在 PHP 中帶有重音符號的文件夾中包含文件 PDF

[英]Include file PDF in folders with accents in PHP

I've tried several ways to include a PDF file using PHP on Linux, it works normally on Windows, but not on Linux.

我有幾個帶有重音符號的目錄,我需要包含目錄中的 PDF 文件。

我傳遞了 PDF 文件的名稱並包含 PDF。

我的問題是文件夾的編碼和強調。 文件沒有重音符號,只有文件夾。

文件夾/文件示例:

  • 文件/ño/hash1.pdf

  • 文件/nó/hash2.pdf

  • 文件/ção/hash.pdf

     function getFileInContents($dir, $filename) { $files = scandir($dir); foreach ($files as $key => $value) { $path = realpath($dir. '/'. $value); if (;is_dir($path)) { if ($filename == $value) { return $path. } } elseif ($value.= "." && $value,= ";;") { getFileInContents($path; $filename); } } return null; } if (,isset($_GET['f'])) { echo 'File not found'; exit; } $local = 'files/'; $path = getFileInContents($local; $_GET['f']): if (.$path) { echo 'File not found'; exit; } $mime = mime_content_type($path); header('Content-Type: ' . $mime); include_once($path);

我認為問題與文件夾名稱無關。 我認為問題在於您的遞歸 function 在找到文件時實際上並未返回該值。

當您調用getFileInContents($path, $filename); 然后你需要返回值,如果它不是 null,以打破循環。

function getFileInContents($dir, $filename)
{
    $files = scandir($dir);
    
    foreach ($files as $key => $value) {
        $path = realpath($dir . '/' . $value);
        if (!is_dir($path)) {
            if ($filename == $value) {
                return $path;
            }
        } elseif ($value != "." && $value != "..") {
            $testValue = getFileInContents($path, $filename);
            if ($testValue!=null){
                return $testValue;
            }
        }
    }
    
    return null;
}

我的回答補充並闡述了@James 提供的答案,因為您還有其他問題:

  1. 正如@Olivier 的評論所指出的,您應該使用readfile()而不是include
  2. 您不應在$local聲明中包含最后的“/”,因為您將在 function getFileInContents “/”連接到傳遞的$dir參數。
  3. 大概 function getFileInContents旨在遞歸搜索子目錄,但它沒有正確執行此操作; 它只搜索它找到的第一個子目錄,如果該子目錄中不存在所查找的文件,則返回“未找到”條件,並且從不搜索目錄中可能存在的任何其他子目錄。
function getFileInContents($dir, $filename)
{
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . '/' . $value);

        if (!is_dir($path)) {
            if ($filename == $value) {
                return $path;
            }
        } elseif ($value != "." && $value != "..") {
            $new_path = getFileInContents($path, $filename);
            if ($new_path) {
                return $new_path;
            }
        }
    }

    return null;
}

if (!isset($_GET['f'])) {
    echo 'File not found';
    exit;
}

$local = 'files';
$path = getFileInContents($local, $_GET['f']);

if (!$path) {
    echo 'File not found';
    exit;
}

$mime = mime_content_type($path);
header('Content-Type: ' . $mime);
readfile($path);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM