PDA

View Full Version : PHP variable content


jondaapplegeek
2008-02-14, 09:36
I'm redesigning my website, and having a go a very small, simple pieces of PHP.
I want to have my main design, then call in the main content from an additional html page (for this example, about.html). So, to get on my about page, i think the URL should look like this:

jonhole.co.uk/index.php?page=about

And the code in the index.php page, in the DIV where I want my content, I think should look like this:

<?php @ require_once ("$page.html"); ?>

But there is obviously something wrong somewhere! Sorry for asking such a simple question, but I just got so confused with what the various websites where trying to say!

Thanks

noleli2
2008-02-14, 09:49
The reason it's not working is that the $page variable doesn't exist. Variables in the URI are in the $_GET global array, so you'd access it like $_GET["page"].

I'm also not sure what the difference is between require and include (because I haven't bothered to look it up), but I've used include in the past.

chucker
2008-02-14, 09:53
noleli2 has already explained why the above doesn't work and how to fix it, but what you're doing is quite dangerous. Using a URL like jonhole.co.uk/index.php?page=../someOtherFile, I could access a HTML file outside the intended path. You'll want to have some function that sanitizes the GET parameter as to avoid this issue.

I'm also not sure what the difference is between require and include (because I haven't bothered to look it up), but I've used include in the past.

http://php.net/require
require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless.

rollercoaster375
2008-02-14, 10:36
In addition to the stuff that they've mentioned... It's bad practice to use variables directly within double quotes, especially when you're appending directly to the variable's data.

Better options:
require_once ( $_GET['page'] . ".html" );
require_once ( "{$_GET['page']}.html" );

Although, I'm sorta confused as to why you're including an HTML file...

Edit: Oh, and you probably don't want to silence error messages on includes.

Wyatt
2008-02-14, 12:39
I think it's really a much better idea to have your design in PHP includes.


<?php require "header.php"; ?>
<!-- Page content -->
<?php require "footer.php"; ?>


With this, you just put everything that goes above the main content in the header.php file and everything that goes below in the footer.php.

This way, you're not running the risk of somebody messing with the query string, you come up with much cleaner URLs and it's still easy as pie to redesign.