I am making a custom theme in WordPress. Now inside the theme folder is another folder named "php" with a text file in it, let's say "names.txt". Now what I want to do is read the text file from the "php" folder. I have this codes in my index.php:
<?php
$file = fopen("/php/names.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
But my webpage is stuck in infinite loop, with errors that the file doesn't exists though it does. Badly need help. UPDATE: I tried running the codes above in a separate php.file which I placed in the same directory with the "names.txt" file, and it reads the data.
UPDATE [SOLVED]:
<?php
$location = get_template_directory() . "/php/admin.txt";
if ( file_exists( $location )) {
$file = fopen($location, "r");
while(!feof( $file )) {
echo fgets($file). "<br />";
}
fclose($file);
}
else
{echo "no file.";}
?>
Works like magic, thanks to @MackieeE
Start off by doing a better check system for the file, using
file_exists()
:Then let's look on how you're calling the file from - it's probably just unable to find it! Currently, your WordPress script is probably calling it from the themes folder as below:
Although as mentioned, the current script is looking for it in:
Because of the starting slash within your
/php/
Make sure you're placing your names.txt in the correct location, you can use Wordpress'es pre-defined variables
get_template_directory()
or PHP's$_SERVER["DOCUMENT_ROOT"]
to make sure you point to the correct folder if need be: