views:

787

answers:

5

I've stumbled upon the following pecularity:

$handle = fopen(realpath("../folder/files.php"), "r");

can't read a file, but as soon as I remove php tags from the file, it becomes readable and my scripts prints non-empty file content on the page. Also, file.php is never ever executed, so I wonder why it is the problem.

I guess somehow Apache or PHP doesn't let read files containing php tags PHP as just text.

How can I enable it for my particular file (course doing it globally would be unsecure)?

Using PHP 5.2.x and Apache 2.0

A: 

Hmm file_get_contents() is working for me. Is it issue only for fopen?

Edit: what error do you get exactly?

Alekc
Unlikely, I've just tested - file_get_contents() has the same problem for me.
PHP thinker
+4  A: 

Are you sure you're interpreting the output correctly? If you print the file contents directly to your page output, a browser won't display text inside angle brackets because it thinks it's a tag. Serve your content as text/plain, or use your browser's "view source" command to make sure you're looking at what's really there, and not just what the browser chose to display.

Rob Kennedy
I agree. I am able to print everything except the the tags inside <> . But one of test page displays button which is in the php file being read.
Shoban
View source in Google chrome hides the php tags for some reason...
Wadih M.
+9  A: 

I got it. I was using Google chrome to debug the page, and I realized that when viewing the source, Chrome hides PHP tags for some reason. I ran the same test on Firefox, and viewing the source proved that everything was okay.

Here are the test details:

Code:

$fh = fopen("test.php","r");
while ($line = fgets($fh)){
echo $line;
}

File to be read (test.php):

testing <?php testing2 ?> testing3

Rendering (on both Chrome and firefox):

testing  testing3

View source (using firefox):

testing <?php testing2 ?> testing3

View source (using Chrome - source of my mistake):

testing  testing3
Wadih M.
You really got it. That was the case!
PHP thinker
That's a pile of lame. Firefox used to do something similar, where it would alter the source of the document when you viewed sourse. (basically showing you the "this is how I interpret that invalid HTML) Because of that I started using curl to debug HTML output.
Alan Storm
Right. Thanks for the insight, Alan. With curl, things most probably can't go wrong.
Wadih M.
ALso to make sure that doesn't happen in the future you could do something like: echo htmlspecialchars($line); or echo str_replace('<?php', '<?php', str_replace('?>', '?>', $line));
Pim Jager
A: 

Wadih M. solved the issue. PHP tags hides the whole tag-enclosed php source output in the browser, but View Source shows them. Thanks!

PHP thinker
You're welcome PHP thinker. Simply set the reply as a solution (big green check sign) to close the question. Thanks
Wadih M.
A: 

rename the file read it get your data change them rerename your file :)

Omar Abid