Monday, February 21, 2011

PHP file print its own content

Is it possible for PHP file to print itself, for example <?php some code; ?> that I get output in HTML as <?php some code; ?>(I know its possible in c++), if not is it possible to actually print html version of php code with nice formatting and colors such as from this url inside code container http://woork.blogspot.com/2009/07/twitter-api-how-to-create-stream-of.html. OR from this website when you press code, while posting your example your code gets wrapped or whatever term is for that, makes it distinguishable from other non-code text. tnx

From stackoverflow
  • Yes.

    <?php readfile(__FILE__)
    

    __FILE__ is a magic constant that contains the absolute filesystem path to the file it is used in. And readfile just reads and prints the contents. And if you want to have a syntax highlighted HTML output, try the highlight_file function or highlight_string function instead.

    Tom : Of course, you'd want to run it through htmlentities() and posiblely wrap it in
     
    so that it would display correctly.
    c0mrade : So lets say if I wanted to print content of index.php from print.php , my code would be
    Gumbo : @c0mrade: Yes, that would print the plain contents (so the source) of that *index.php* directly to the client. If you want to print it in a HTML file, use `file_get_contents` instead of `readfile` and pass it through `htmlspecialchars` to replace HTML’s special characters. So: `echo htmlspecialchars(file_get_contents("index.php"));`
    c0mrade : Yes it totally worked
  • I'm not sure if this is exactly what you want but you can print a file using:

    echo file_get_contents(__FILE__);
    

    or syntax-highlighted:

    highlight_file(__FILE__);
    

0 comments:

Post a Comment