March 20, 2012

PHP Echo and Includes

Question by Kevin Schueller

When I use the following PHP code:

$id = $_GET['page']; $page = include ($id.'.php'); echo $page;

The code within the $id.php file is returned, however there is a “1” appended to it, any idea why this is happening?

Answer by Marc B

include() will return boolean TRUE if the file was successfully included. You then echo out that true value, which is printed as a 1.

Of note: never directly use user-provided data ($_GET[‘page’]) in file system operations. It’s a hideious security risk. You’ve at least got .php being appended so it’s not quite as large a gaping hole, but still… don’t do this.

Answer by Starx

  • You shouldn’t echo a page like that.

    include() is used to import the document onto your current working file.

  • By using $page = include ($id.'.php');, you are assigning boolean value to $page

    This will hold the success status of the include() statement

    • If the page load successfully, it give true, whose numeric value is 1
    • If the load was unsuccessfully, it gives false, whose numeric value is 0

However, the way you are using is not entirely incorrect

For example: Create a page Test.php to return a value at the end

$t = “some text”;
return $t;

Then you will able to use it to echo

echo include("test.php"); //outputs "some text"

I suggest you tead the documenation for complete guide

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!