Include Dynamically Named Files - php

I'm just curious how I can include a PHP file that doesn't have a static name like home.php, or contacts.php?
I want to have it so when I click on a link it includes the name of the page I was sent to.
So, I click on "Contacts", instead of my code being:
<?php include "contacts.php"; ?>
It's:
<?php include "somekindofcodetohavethisdynamic.php"; ?>
Is there a way to do this?

There should be some logic that returns the dynamic stuff, right? Put that into a function:
function getDynamicName($page) {
// Magic happens here.
}
And, get it stored in some variable. And include it in the normal way.
$contactPage = getDynamicName("contact");
include "{$contactPage}.php";
If you are very lazy, you can do this as well:
include getDynamicName("contact") . ".php";

Related

custom field inside of an include

Hello I am trying to include a custom field from wordpress inside of a php include.
Heres what the custom field call looks like:
<?php the_sub_field('icon_number'); ?>
What I want to do, is place this code inside of a php include path.
So heres what it would look like manually:
<?php include("svgs/icon-1.php"); ?>
So combined I have:
<?php include ('svgs/icon-' . the_sub_field('icon_number') . '.php'); ?>
Some reason it is just spitting out the number instead of the include path.
Heres my second attempt using a variable:
<?php
$iconNumber = the_sub_field('icon_number');
include ('svgs/icon-' . $iconNumber . '.php');
?>
Still same output, just the numbers.
Did I mess something up?
-Joe
You want get_sub_field not the_sub_field. Generally speaking, the get_ functions will return a value for you to use, and the_ functions will forcefully echo the value that's returned.

php include 'head' secton of html doc, if

i have a lot of pages, most all have head sections and can 'stand alone'.
Also, most of them get 'included' in 'larger' documents or articles.
So, in a, lets call it a 'big page' I could have 3 or 4 included pages, all having their own head information.
Is there a fancier way to include a 'head.html' with all the meta's, style etc, BUT only once so that if the 'parent', lets say index.php has already 'included' 'head.html' the inclusion of say, specialcharacters.html will Not also load a head, but if I were to load specialcharacters.html on it's own, it Would 'include' the 'head.html'????
(exp: index.php includes, nav.html, nav_r.html, header (logo, welcome etc), footer.html, body01.html, specialcharacters.html, etc.. BUT, i want to use specialcharacters.html as a stand alone document with head, style etc for doc formating Also.)
so, some kind of include if... so head.html is only included Once.
I hope that is relatively clear..
Thanks you, in advance,
Landis.
landisreed dot com/index.php - head.html
I suppose you can use
include_once 'header.html';
Then if it was included before it won't be included again.
This said you would have to include header information into every file, so your specialcharacters.html will have to use it as well as body01.html. Then whichever include_once first - there header.html will appear.
EDIT:
To differentiate titles or other information you can do as follows in header.html:
<title><?=$title;?></title>
And then in every of your scripts
$title = 'Whatever';
include_once "header.html";
Now, whoever calls header first will set the $title first and render it inot the header. Once its rendered into header, subsequent changes of $title by any other includee will simply be ignored by your page.
have you tried using 'include_once'? http://www.php.net/manual/en/function.include-once.php
Example:
include_once "header.php";
include_once() is what you can use, according to PHP's documentation
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again.
As the name suggests, it will be included just once.
more information here http://in3.php.net/include_once
If I got the question right, I think what you need is a single Header file header.php to be included in all pages with require_once. The trick isto put all different kinds of heads you have , like one for head.html and one for specialcharacters.html, into the header.php file separated by if statements. The header.php might look like this :
if ($caller == 'head') { // HTML for head.html}
elseif($caller != 'head' && $caller == 'specialcharacters')
{ // HTML specific to specialcharacters.html for standalone viewing}
Once this header.php is written with all conditions in place, you need to set $caller accordingly at the top of each file (e.g. for specialcharacters.php first line of code should be $caller = 'specialcharacters';. Then include header.php to all files as require_once("header.php") just after specifying $caller.
EDIT
Your index.php file will look like this:
$caller = 'in_my_index';
require_once('header.php');
Your specialcharacters.php file will look like this:
$caller = ($caller != 'in_my_index')?'in_my_specialchars':'in_my_index'; // This is to make sure that when specialcharacters.php is included inside index.php then it should still show index.php title but when loaded standalone, it will show its own title.
require_once('header.php');
Now your header.php looks like this :
<html><head>
<?PHP if($caller == 'in_my_index') { echo '<title>I am Index Title</title>';}
elseif($caller == 'in_my_specialchars') { echo '<title>I am standalone Specialcharacters.php Title</title>';}
?>
This should give a better idea I hope.
Hope this helps!

Dynamic site, using include to get content in specific div , how?

I want to use php to easily maintain my website, but I simply can't figure out the language - I've found some tuts online, and some other questions here, but none help me.
I've divided my site into some .php files, header/footer and such - And using
works fine..
Now I want the content of my site, to update according to which menu I click on at my site.
http://dawtano.com/pp/
If I click on "about" I want the "Hello World" to open inside my content div, but I can't get the right php code to do it.
I think you should do this---
Note: This will only work if the CSS styling are on the current directory! ()
<div>
<?php
$html_page = implode('', file('http://dawtano.com/pp/'));
echo $html;
?>
</div>
Hope this helps!
well currently your links are taking you to a separate page entirely. So why not just code it so that your include file is specific to the page. i.e, on about.php, use something like
include 'about_content.php
in your contetnt div.
If you're looking for your content to load dynamically into the content div you'll need to look into using ajax to fetch the content pages.
One popular way to construct the site is to have a single php script which displays content based upon a $_GET variable like 'page' or 'content', and then make the link as:
'http://dawtano.com/pp/index.php?page=helloworldcontent'
Using this method, you would need to check if the variable ($_GET['page']) is set using isset(), and then make sure the string is safe... as anybody with a browser could just type in some mumbo-magic script and hijack your site:
'http://dawtano.com/pp/index.php?page=somecleaverlycraftedhax'
Once it exists and is safe, add the '.php' to the file name and include that file... if it exists! If it doesn't exist, then you will need some code to handle that, probably by displaying a 'File not Found' message, or redirecting home, or something.
I prefer not to do this because it is a pain to make safe, and I feel like it is pretty ugly. What I do instead is put all the header/footer/navbar/title bar scripts into seperate 'display' functions, and put them in another file.
Then include this file with the function definitions, and call all the 'display' functions to set up the page. So every php script in your site might look like:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION, etc... */
print_html_pre_content();
print '<p>Hello, world!</p>';
print_html_post_content();
?>
Since every script will have this structure, you can just create a template file once. When you want to create a new page for your site, copy the template, rename the copy to the php filename you want, and add content between the two print functions.
You also keep the ability to modify the header/footer/navbar/title bar for the whole site in a central location, namely the included file with the functions.
You might be looking for some sort of Template Engine which allows you to create your pages out of variable parts. You could have a look at TBS, which is more or less what is suggested by the name. But there is a whole lot more engines out there which could do the job.
If that's already too much over the top, maybe Apache SSI (Server Side Includes) are a try for you.
A little suggestion from my side, I am often using Apaches mod_rewrite in connection with a single controller.php file. Apaches mod_rewrite will then send all request to the controller.php which will fetch the appropriate page parts for the requested page using TBS and return the respective page. So you have the controll of the page in one location only.
To your original question about.php could look like:
<?php
include('header.php');
?>
// original page content as html for about.php
// assuming header ends with the starting div <div> where you like the content to appear
// and footer starts with the closing div </div>
// if you need variable content here, simply use <?php echo $your_variable ?>
<?php
include('footer.php');
?>
The best way would be to use a switch statement:
http://php.net/manual/en/control-structures.switch.php
Something like this:
<?php
include("header.php");
$page = $_GET['page'];
switch($page)
{
case "about":
include "about.php";
break;
case "faq":
include "faq.php";
break;
case "help":
include "help.php";
break;
default:
include "home.php";
}
include("footer.php);
?>
Then just make all of your links look like this:
http://www.example.com/index.php?page=home
Just replace home with the correct page.

include header vs include page

I'm currently using include 'header.php' and include 'footer.php' in every page, and as far as I know that's how most people do it. I thought of a way that I personally thought would be better, however. I thought of making index.php, then in the index include the page. This would both eliminate the need for a footer and eliminate the need for include twice in every page. I'm really new to php, however, so I don't know how I would do this. I tried using POST and GET methods, but it doesn't seem to work. What I want to achieve is including pages in the header using a URL such as http://mysite.com/index.php?page=history and then load history.php. If I need to clarify something, just ask. Sorry if I don't accept an answer right away, I'm really drowsy. I'll get to it when I can.
It is not a problem if you include 2 pages in a file, like header.php and footer.php...
Just writing 2 lines of code in each page is not a matter.
You can decide what pages you want to include dynamically in every page by using if statement, instead of passing the page name in the url.
If you'll do it via index.php, you will no doubt do it wrong.
Nothing bad - every newbie does it this way.
Just because you're thinking of includes, while you should be thinking of templates.
You can make it via index.php, no problem. But there should be not a single HTML tag in this index! As well as in the actual page.
No matter if you're doing it in separate pages or via index.php, the scenario should be the same:
Get all data necessary to display particular page.
Call a template.
Thus, your regular page would look like
code
code
code
include 'template.php';
while index.php would look like
get page name
sanitize page name
include page
include 'template.php';
now you can decide what to choose
First off i agree with Meager... Take a look at soem frameworks. Most will use a two step view which essentially does this althoug in a more complex and flexible way.
With that said it would look something like this:
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'home'; // default to home if no page
if(file_exists($page.'.php')) {
// buffer the output so we can redirect with header() if necessary
ob_start();
include($page.'.php');
$content = ob_get_clean();
}
else
{
// do something for error 404
}
?>
<html>
<head></head>
<body>
<?php echo $content; ?>
</body>
</html>
You could get more complex than that. One thing you want to do uis make sure you dont blindly assume that the page in the $_GET var is safe... make sure the file exists on your server or otherwise sanitize it...

Having includes with variables in two places at once

I have a small situaton here. I'm building a custom CMS for one of my websites.
Below is the code for the main index page:
<?php
require("includes/config.php");
include("includes/header.php");
if(empty($_GET['page'])) {
include('pages/home.php');
} else {
if(!empty($_GET['page'])){
$app = mysqli_real_escape_string($db,$_GET['page']);
$content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM pages_content WHERE htmltitle = '$app'")) or die(mysqli_error($db));
$title = $content['title'];
$metakeywords = $content['htmlkeywords'];
$metadesc = $content['htmldesc'];
?>
<h1><?php echo $content['title']; ?></h1><hr /><br />
<div id="content"><?php echo $content['content']; ?></div>
<? } else { include('includes/error/404.php');} }
include('includes/footer.php'); ?>
The file, includes/header.php contains code to echo variables, such as, page title and meta stuff.
The issue is that when the include("includes/header.php"); is where it is, outside of the if conditions, it will not echo the varables, obviously, however, I can't put the include in the if condition otherwise, the home page, which does not require any url variables will show without these conditions.
What do I do?
You can't really write code like this for too long. It's ok to for start, but you will soon realize it's hard to maintain. The usual way is to split it into a few steps.
First check input and determine on which page are you
If you know you are on the homepage, include something like includes/templates/homepage.php
Otherwise try to load the page from the database
If it worked, include includes/templates/page.php
Otherwise include includes/templates/404.php
Each of the files in includes/templates will output the whole page, i.e. they all include the header, do something and include the footer. You can use for example Smarty templates instead of PHP files, which will make the approach obvious.
Once you have this, you can split the code even more. Instead of loading the page directly from index.php, include another file which defines a function like load_page($name) and returns the page details.
Then a few more changes and you realize you are using the MVC approach. :) The functions that load data from the database are your Models, the Smary templates are Views and the PHP files that put them together are Controllers.

Categories