在PHP中对readfile()函数使用alert


Using alert for a readfile() function in PHP

我有这段代码,我想查看/保存正在显示的文件(.txt)。保存的代码正在运行,但我希望"查看"选项使用警报显示文件的内容(我尝试了新选项卡,但它在地址栏中显示了路径,我不希望发生这种情况)。

问题是它显示了最后一个显示文件下的内容,而它在警报窗口中显示的只是一个数字。是否可以在警报窗口中显示文件的全部内容?

    $dir = "C:/xampp/htdocs/www/backup";
echo "<center>";
echo "<h1>Logs</h1>";
// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
        if ($file == '.' or $file == '..'){ continue;}
        echo $file."<a href='?link=$file'>[VIEW]</a>&nbsp;<a href='?link1=$file'>[SAVE]</a> <br>";
    }
    echo "<br>";
    closedir($dh);
  }
}
//View File
if(isset($_GET['link'])){
$link=$_GET['link'];
    if (is_dir($dir)){
        if ($dh = opendir($dir)){
            while (($file = readdir($dh)) !== false){
                if ($link == $file){
                        $file = 'C:/xampp/htdocs/www/backup/'.$link;
                        if (file_exists($file)) {
                            //header('Content-Disposition: attachment; filename="'.basename($file).'"');
                            $read = readfile($file);
                            echo "<script type='text/javascript'> alert($read); </script>";
                            exit;
                        }
                }
            }
        }
    }
} 

readfile读取文件并将其直接写入输出缓冲区,即直接发送到浏览器。

例如,将readfile更改为file_get_contents()

您可能需要将生成的字符串用引号括起来,使其成为有效的javascript。

$read = file_get_contents($file);
echo "<script type='text/javascript'> alert('$read'); </script>";
exit;