Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include a text file in PHP as PHP, without printing to the page?

Tags:

php

I am making myself a webpage that simply redirects to one of a list of other websites upon page load. In order to be able to edit the list of sites more easily, I moved the list to a separate text document. Upon including the file in the PHP code, the browser reverts to parsing HTML and back again when the include is over. As a result, my code gets printed to the screen rather than executed. I am unable to implement PHP headers and tags within the text file, since that would defeat the purpose of keeping it external. As it stands now I have another script that allows me to append links to the file if I want to add them.

index.php, the file I am working with

    <?php 
        $array_content = array(include 'sites.txt');
        header("location: ".$array_content[rand(0,9)]);
    ?> 

sites.txt, the file I am including

    "http://www.nsa.gov/"
    ,"http://www.youtube.com/watch?v=oHg5SJYRHA0"
    ,"http://leekspin.com/"

Is there a way to just insert the text file into index.php, without printing it to the screen?

like image 262
Jacob Avatar asked Dec 16 '22 06:12

Jacob


2 Answers

You should not!

Parse it as text (eg. by stripping the content of spaces and splitting it by commas) or, less preferably, make the content a PHP code and then include it using include.

Parsing TXT file as text

You should probably stick to parsing the file as text - you can use file() function for this. file() reads the whole file and returns its content as array of lines (with end of lines still attached). You can do whatever you need with such data (eg. strip it off the commas and spaces).

PHP code within included file

If you choose the former (including PHP code in TXT file, which is a bad idea if you want to make sites.txt available publicly), then you should try not to pollute global namespace. You can achieve it by using solution mentioned by other answers:

  • in sites.txt:

    <?php
    return 'your string goes here';
    
  • in your script:

    <?php
    $my_string = include('sites.txt');
    

The worst solution - eval()

Just including it for informative reasons. If you have a PHP code within your TXT file, you can use eval() for parsing it as PHP code. But remember - eval() is evil, avoid it at all costs.

like image 118
zizozu Avatar answered Mar 23 '23 00:03

zizozu


What you want is PHP's parse_ini_file() fn:
http://php.net/manual/en/function.parse-ini-file.php

You can easily then manage your list in a separate file and import it as an array for use without much fuss.

like image 24
Jakub Avatar answered Mar 22 '23 23:03

Jakub