I am aware there are more topics on this matter, I've read them, but I did not found the answer.
I have an index.php, that contains a bunch of .php includes: header.php, navigation.php, box.php, footer.php, and inside the "pages" div, I have the one that needs to be different (based on the links from navbar.php or box.php).
navbar.php example:
<a href="index.php?v=pag1.php">Page1</a>
<a href="index.php?v=pag2.php">Page2</a>
index.php:
<div id="wrapper">
<div id="header">
<div id="topbox">
<?php include ("box.php"); ?>
</div></div>
<div id="content">
<div id="bara">
<div id="navbar">
<?php include ("navbar.php"); ?>
</div>
</div>
<div id="pages">
<?php include ("$v"); ?>
</div>
</div>
<div id="footer">
<?php include("footer.php"); ?>
</div>
</div>
I have a $v='pag1.php', $v='pag2.php' , etc on each page I want to include, but I get "undefined variable" error "Undefined variable: v in C:\wamp\www\test\index.php on line 39"
If I define the variable $v inside of index.php, it works, but that means I will have to create duplicates of index.php, and kinda defeats the purpose. I only want pag1.php, pag2.php, pag3.php, etc to be included in index.php, not to create a lot of copies. I can use html for that :)
I know I probably ask a stupid question, but I'm a newbie in php, and I have no idea where to look for answers. Thank you in advance.
Strictly speaking, all you need is to change
<?php include ("$v"); ?>
to
<?php include $_GET['v']; ?>
A couple things to note here:
$_GET
array, not independent variables. include
doesn't need parenthesis. It's not wrong to include them, but it's not necessary. See the documentation.So, that all in mind, a much better implementation for index.php would be:
<?php
$v = "content/home.php"; // default page
if (isset($_GET['v'])) { // if the GET variable is set. If no v parameter is provided, asking for $_GET['v'] will cause an error in strict mode.
$v = "content/" . $_GET['v'] . ".php"; // keep some control on what can be opened.
}
if (!file_exists($v)) {
header("HTTP/1.0 404 Not Found"); // this has to be called before ANY content is sent (include newlines).
$v = "content/404.php";
}
?>
<div id="wrapper">
<div id="header">
<div id="topbox">
<?php include "box.php"; ?>
</div></div>
<div id="content">
<div id="bara">
<div id="navbar">
<?php include "navbar.php"; ?>
</div>
</div>
<div id="pages">
<?php include "$v"; ?>
</div>
</div>
<div id="footer">
<?php include"footer.php"; ?>
</div>
</div>