从php中的本地磁盘读取文件


Reading in files from local disk in php

我已经从svn下载了文件,这些文件现在存储在本地磁盘上的文档中。这些文件大多是php文件。我如何读取位于本地磁盘上的文档(不是"txt"),并在使用php的网站上打开它们。到目前为止,这就是我所拥有的,

index.php

<script>
$(function() {
    $('#getData').click(function(event) {
        event.preventDefault();
        $.ajax({
            type: "GET",
            url: "endPoint.php",
            data : { field2_name : $('#userInput2').val() },
            beforeSend: function(){
            }
            , complete: function(){
            }
            , success: function(html){
                //this will add the new comment to the `comment_part` div
                $("#displayParse").html(html);
                //$('[name=field1_name]').val('');
            }
        });
    });
});
</script>

<form id="comment_form" action="endPoint.php" method="GET">
    Enter the file you would like to view:
    <input type="text" class="text_cmt" name="field2_name" id="userInput2"/>
    <input type="submit" name="submit" value="submit" id = "getData"/>
    <input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id="displayParse">
</div>

endPoint.php

<?php
$filePath = $_GET["field2_name"];
$url = "cs_data/home/" . $filePath;
$file = fopen($url, "r");
fread($file,filesize($url));
echo '<div class="comment">' . $file . '</div>';

?>

基本上,用户输入一个他们想要打开的文件,这些文件位于我的本地磁盘上。不确定哪里出了问题,因为文件内容没有打印出来,而是打印出了"资源id#3"。此外,我正在使用MAMP在localhost上运行我的代码。我使用的IDE是phpstorm。我不确定我的文档是否需要加载到phpstorm上才能访问它们

fread返回您感兴趣的字符串。因此,您没有检索文件的内容,所做的基本上是打印文件php引用!试试这个:

$filecontent = fread($file,filesize($url));
echo '<div class="comment">' . $filecontent . '</div>';

$file"is"文件资源;您不想打印它,而是打印fread()的返回值,即文件的内容
但话说回来,你不想发送文件的"原始"内容,因为它可能(也可能)包含会破坏你的html结构的内容
至少你应该使用htmlspecialchar()

<?php
$filePath = $_GET["field2_name"];
// you really should add more security checks here
// just imagine a request like field2_name=../../../etc/something.txt
$url = "cs_data/home/" . $filePath;
$contents = file_get_contents($url);
echo '<div class="comment">', htmlspecialchars($contents), '</div>

您可能还对highlight_file()感兴趣:

<?php
$filePath = $_GET["field2_name"];
// you really should add more security checks here
// just imagine a request like field2_name=../../../etc/something.txt
$url = "cs_data/home/" . $filePath;
echo '<div class="comment">';
highlight_file($url, false);
echo '</div>';