Kevin Schueller
Kevin Schueller

Reputation: 77

PHP Echo and Includes

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?

Upvotes: 0

Views: 138

Answers (5)

Starx
Starx

Reputation: 78971

  • 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

Upvotes: 2

Alexandru R
Alexandru R

Reputation: 8823

Most probably because include will return true or false (0 or 1). Actually you include the page content and then echo $page. This will print "1".

Hope you got it. Don't echo $page at the end. Just use include.

Upvotes: 0

rjz
rjz

Reputation: 16510

Yes! When you include, you're just telling PHP to parse the additional file as well. The variable you've set--$page-- just contains the return value of the include() function. Since it's 1, I'd say you included the other file successfully.

On a related note, it's generally (meaning, almost never) a good idea to include an arbitrary file based on un-parsed parameters from a user request. By manipulating the value of page passed to your script, a theoretical attacker could get your machine to execute any PHP file in the system--a dangerous proposition!

Upvotes: 1

AlvaroGMJ
AlvaroGMJ

Reputation: 416

because the 1 is the return code of the include(), which you are saving in the $page variable.

The code within $id.php is returned when you do the include(), the only thing your 'echo' is printing is the 1

Upvotes: 1

Marc B
Marc B

Reputation: 360612

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.

Upvotes: 2

Related Questions