繁体   English   中英

从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>';


?>

基本上,用户输入了他们想要打开的文件,并且这些文件位于我的本地磁盘上。 不知道我哪里出错了,因为文件内容没有被打印出来,而是我把它打印出来了“ Resource id#3”。 另外,我正在使用MAMP在本地主机上运行代码。 我正在使用的IDE是phpstorm。 我不确定是否需要将我的文档加载到phpstorm上才能访问它们

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

$filecontent = fread($file,filesize($url));

echo '<div class="comment">' . $filecontent . '</div>';

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

<?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>';

暂无
暂无

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

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