0

Versions of this question have been asked before, but I am still none the wiser about how to make PHP read any content from a file and use it as a variable - whether the first line, a defined number of characters, or the whole thing - and then echo it back to an .html page. So I have tried to simplify this question right down.

I have the following three files at the paths shown (this is exactly how the paths look to my FTP program, except that I have made "my_username" and "my_domain" generic) and with the contents shown:

my_username/my_domain/test.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html>  
<head>  
</head>
<body>
Yes!
<?php include ("../new-dir/testprogram.php"); ?>
</body>
</html>

my_username/new-dir/testprogram.php:

<?php
echo file_get_contents("testfile.txt")."No";
?>

my_username/new-dir/testfile.txt:

Hello, I am testfile.txt!
This is the second line in this file.
This is the third.

When I browse to my_domain.com/test.php I simply get a webpage saying

Yes! No

As you can see, the inline PHP on the client side is reading the PHP on testprogram.php on the server side, and the echo command in the latter code is being executed. The problem is that echo is only acting on what comes after the ".", namely the word "No". I have tried hard to debug this, and the above is the simplest showcase of the problem I have arrived at so far. I have just not been able to get PHP to demonstrate that it has processed anything at all from the file testfile.txt. It is as if the function file_get_contents is being ignored, even though I copied the contents of my file testprogram.pgp from the example usage of this function given on its page in the PHP documentation at W3schools.com. For debugging purposes I only made a single alteration, namely by tacking on "No" as a second argument of the echo function - and that's not the problem. I'd be very grateful for any help with this.

  • Try `file_get_contents(__DIR__ . "/testfile.txt")`. See [Magic constants](https://www.php.net/manual/language.constants.predefined.php) Also, it's pretty odd to have PHP code in an `.html` file – Phil Feb 08 '21 at 00:34
  • See also [How can I get useful error messages in PHP?](https://stackoverflow.com/questions/845021/how-can-i-get-useful-error-messages-in-php) – Phil Feb 08 '21 at 00:37
  • PHP's include path is often a point of confusion. The general advice is to use `__DIR__` to make sure you know exactly where your relative path begins – Phil Feb 08 '21 at 00:44
  • Many thanks, @Phil! That works fine. The page now reads, as it should, `Yes! Hello, I am testfile.txt! This is the second line in this file. This is the third.No`. Apologies - I meant to type "test.php" not "test.html". I'll correct. –  Feb 08 '21 at 00:46

0 Answers0