Pergunta

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

Foi útil?

Solução

Start off by doing a better check system for the file, using file_exists():

if ( !file_exists( "/php/names.txt", "r" )) 
   echo "File not found";

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:

   --> root
      --> wp-content
        --> themes
          --> yourtheme
            --> php
              --> names.txt

Although as mentioned, the current script is looking for it in:

  --> root
    --> php
      --> names.txt

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:

 $location = get_template_directory() . "php/names.txt";
 if ( file_exists( $location )) {
    $file = fopen($location, "r");

    while(!feof( $file )) {
        echo fgets($file). "<br />";
    } 

    fclose($file);
 }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top