File exists but PHP throwing “failed to open stream: no such file or directory”

I am trying to pull a random string from a .txt file on my server in order to display it in the footer of my site. Here is the code I am using (the first two lines are purely for debugging purposes):

<div id="footer">
    <div class="instructions">
        <?php
            $file = include_once 'facts.txt';
            echo dirname(__FILE__);
            $f_contents = file('facts.txt');
            $line = $f_contents[array_rand ($f_contents)];
            echo $line;
        ?>
    </div>
</div>

And here is what gets displayed in my footer:

Read More
TEST LINE - FOR TESTING PURPOSES.

/HOME/LEWIHTYV/PUBLIC_HTML/WP-CONTENT/THEMES/LEWNACY

WARNING: FILE(FACTS.TXT) [FUNCTION.FILE]: FAILED TO OPEN STREAM: NO SUCH FILE OR DIRECTORY IN /HOME/LEWIHTYV/PUBLIC_HTML/WP-CONTENT/THEMES/LEWNACY/FOOTER.PHP ON LINE 6

WARNING: ARRAY_RAND() EXPECTS PARAMETER 1 TO BE ARRAY, BOOLEAN GIVEN IN /HOME/LEWIHTYV/PUBLIC_HTML/WP-CONTENT/THEMES/LEWNACY/FOOTER.PHP ON LINE 7

For some reason, even through the file is being recognised when being included and the directory is correct (the footer.php and facts.txt files are both in the same directory), the random line selection is throwing this error. I have tested this code locally using WAMP and I have had no problems whatsoever. I have also checked the file permissions to make sure it is readable.

Related posts

Leave a Reply

1 comment

  1. The answer is PHP doesn’t automatically assume that “facts.txt” is in the same directory as the PHP file that’s running. You have to tell it the full path.

    Try:

    $f_contents = file(dirname(__FILE__) . '/facts.txt');