3

How to read a .php file using php

4
  • 1
    You can just include the file, no? Commented Jan 7, 2014 at 6:37
  • 1
    Why you can not read a .php file? what problem you face? Commented Jan 7, 2014 at 6:37
  • I just get a blank page while reading a *.php file using fgets Commented Jan 7, 2014 at 6:38
  • @Fred-ii- Sorry I dont want to include a file. I just read a file. Commented Jan 7, 2014 at 6:40

3 Answers 3

17

Let's say you have two files a.php and b.php on same folder.

Code on the file b.php

<?php

echo "hi";

?>

and code on a.php

<?php
$data = file_get_contents('b.php');
echo $data;

You access a.php on browser.

What do you see? A blank page.

Please check the page source now. It is there.

But not showing in browser as <?php is not a valid html tag. So browser can not render it properly to show as output.

<?php
$data = htmlentities(file_get_contents('b.php'));
echo $data;

Now you can see the output in browser.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to get the content generated by PHP, then

$data = file_get_contents('http://host/path/file.php');

If you want to get the source code of the PHP file, then

$data = file_get_contents('path/file.php');

Remember that file_get_contents() will not work if your server has *allow_url_fopen* turned off.

3 Comments

I need to get the content generated by PHP as in your first example but without using web server and HTTP requests. Any ideas how to achieve this?
Why do you want to do this? Of course, if you have the file locally you can directly open and see the content. FYI, PHP is running on a web server. You are trying to so something which isn't possible
I want to (write tests, which) verify that the content I get over HTTP request is exactly what I expect it to be. Obviously with dynamic parts being processed. I can't compare the source file to the HTTP response body. I need to compare the processed output without using HTTP with the same sent over HTTP. You may also ask why would I want to do this. A short answer: because I need ;-) A longer one: In order to make sure that problems with a third party middleware outside my domain do not happen again unnoticed.
1
//get the real path of the file in folder if necessary
$path = realpath("/path/to/myfilename.php");

//read the file
$lines = file($path,FILE_IGNORE_NEW_LINES);

Each line of the 'myfilename.php' will be stored as a string in the array '$lines'. And then, you may use all string functions in php. More info about available string functions is available here: http://www.php.net/manual/en/ref.strings.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.