简体   繁体   中英

Including a PHP file within PHP

I have a website which is running a PHP if statement to show content based on the type of file attached, ie Jpg, Txt, MP4.

So my code for showing TXT files is:

if($post_attachment == 'txt'){$display_attachment = "

        <div class=\"sectionDivide\"></div>
        <div class=\"section\">
            <div class=\"articleAttachment\">
                include(\"../a/files/attachments/$post_year/$post_month/$post_id.$post_attachment\");
            </div>
        </div>

    ";}

The problem is that it's not displaying the content of the TXT file, but instead showing the line include("../a/files/attachments/2016/11/161123095119.txt"); in my web page.

How can I get it to display the content of the text file where I echo out $display_attachment ?

The immediate (and crude) way is to use php's string concatenation operator ( . ):

$display_attachment = sprintf('
        <div class="sectionDivide"></div>
        <div class="section">
            <div class="articleAttachment">' . 
    include("/some/path/to/file") . '
            </div>
        </div>
');

A somewhat less chaotic, though still not really readable variant is the use of sprintf() :

$display_attachment = sprintf('
        <div class="sectionDivide"></div>
        <div class="section">
            <div class="articleAttachment">
%s
            </div>
        </div>
',
    include("/some/path/to/file")
);

A clean solution would fetch the result of the inclusion into a string variable and use that.

To display the content of a File include() is the wrong function. include() will load and execute php-code.

You should try to use fread() instead to get the content of a TXT-file: http://php.net/manual/en/function.fread.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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