PHP: How to include code snippets on some but not all pages - php

I am new to PHP and programming in general and hope someone can help me with this.
I am working on building a website where the code for each page is saved in a separate file.
Now I have a couple of code snippets that I want to use on different pages but not on all of them.
My current approach is that I paste them on every file that uses them which duplicates code and therefore supposedly is not good practice.
On the other hand when I use snippets on all pages I have removed them from the single files and store them as separate includes files using PHP's include or require in order to include them on a page, e.g. for the header, the footer and the menu etc. - example:
require_once("includes/header.php");
This works well and I was wondering if there is a similar way I can include the other code snippets as well BUT without having to save each of them as a separate file.
Is there a way for example that I could use functions for this or is there some other common practice ?
Example (just to show what I mean):
<?php
// example of what I would like to include on different pages
echo "<button type="button" class="class1" id="btn1">Button 1</button><br />
<button type="button" class="class2" id="btn1">Button 2</button><br />
<button type="button" class="class3" id="btn1">Button 3</button><br />";
?>
The pieces to insert could be anything but usually they are some small PHP / HTML snippets, like a set of buttons or a div or a dropdown etc.

Make the code snippets inside a function so you can call it on any other page by including the same page everytime.
Let's say we have an index.php page, and we have a test.php that have this code (that we want to include on the index page):
<?php
function hello(){
echo 'Hello World!';
}
hello(); //to print "hello world!" in this particular page
?>
Now, in the index.php page, we put:
<?php
include('test.php');
?>
<h1><?php hello(); ?></h1>

use a single index.php file to handle the rest
index.php
<?php
require_once 'header.php';
if(isset($_GET['page']){
switch($_GET['page']){
case "123":
require_once 'snippet1.php';
break;
case "1234":
require_once 'snippet2.php';
break;
default:
require_once 'notfound.php';
}
}
require_once 'footer.php';

Related

php file showing output from a different file

I am very new to PHP programming. I am trying to write this custom php code in Drupal and seeing this weird behavior. Basically I have two php files which users can hit and the first php file is showing output from the second one. I am not including (include) the second file in the first one.
Home.php - The first file (outputs 'why am i executing' at the end)
<?php include 'HomeView.BL.inc';
//Other links to access second file
?>
HomeView.BL.inc
<?php
include 'db.inc';
include 'dao.inc'; - has a class called IDA_Map
?>
FacultyInternshipDetail.php - The second file
<?php
include 'InternshipDetailView.BL.inc';
?>
InternshipDetailView.BL.inc
<?php
echo "why am i executing";
include 'db.inc';
include 'dao.inc';
?>
Apart from the output from the second file, I am also seeing this error - Cannot redeclare class IDA_Map.
I have read in other posts about 'include_once' but didn't expect re-declaration error since the class (IDA_Map) is declared once per request.
Thank you.
Flip all these to require_once.
<?php require_once'HomeView.BL.inc';
//Other links to access second file
?>
HomeView.BL.inc
<?php
require_once'db.inc';
require_once'dao.inc'; - has a class called IDA_Map
?>
FacultyInternshipDetail.php
<?php
require_once'InternshipDetailView.BL.inc';
?>
InternshipDetailView.BL.inc
<?php
echo "why am i executing";
require_once'db.inc';
require_once'dao.inc';
?>
include breaks when you try to include the same file twice.
Also look up composer and into using a php framework so you dont have to worry about any of this!

How do you include multiple page content in one php include file?

I am wondering how would I include various elements (header, footer, nav), in one php file to be included on various pages, rather than creating multiple php files to be called separately?
In my includes file I have the following code:
<?php
echo '<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> Carnival, Residue, Maudlin</span>.</h1>';
?>
Outputting onto an html page that is running php I have:
<?php include('php-includes/current-elements.php');?>
Is there a way to include a particular div or class, something other than the entire file itself?
I just didnt want to create a separate php include file for every little element that i want to include on the same page.
The code below is what I had within the same include file to call a different element to be displayed on another page.
<?php
function elements ()
{
echo'<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> TESTING</span>.</h1>';
elements();
}
?>
Any help would be great!
It sounds like you are trying to avoid templates. The basic idea is to define a separate file for each of head, footer, nav and include those from your content template.
head.php
<!doctype html> <html> ...
nav.php
<body> <a href=..> page1 </a> <a href=..> page2 </a> <a href=..> page3 </a>
foot.php
</body> </html>
And to create a complete page, you would do:
<?php
include 'head.php';
include 'nav.php'
An article about prune juice.
include 'foot.php';
?>
Now, if I understand correctly, you want to include only one file and be able to generate the various elements (head, nav, whathaveyou). You could do this by wrapping the include statements in functions:
ubertemplate
<?php
function head() { include 'head.php'; }
function nav() { include 'nav.php'; }
function randomElement() { ?>
An article about prune juice. <?php
}
function totalymisguideddynamiccontents() {
echo "<div> foobar <span> moo </span></div>"
}
function() { include 'foot.php'; }
?>
..then in your final page, call these functions:
uberpage
<?php
include 'ubertemplate.php';
?>
<?php head() ?>
<script src=superlib.js></src>
<?php nav() ?>
Yomama so big when she wears a yellow coat people yell TAXI!.
<?php foot() ?>
Finally, if I understand correctly and you think the uberpage approach seems like a good idea, ...then you should probably try it out. That may well be the only way to realize that it is flawed. I don't mean to mock your idea, but there are better ways to approach templates and the first way, the one you are trying to avoid, is cleaner (but that's only my opinion).
For a better way, look at twig templates or do some more research and find a framework that suits your needs.

hide div in a certain html page

apology for this newbie question.
I have created an html page (dash.html) that uses the same header as the other pages.
it calls this PHP function <?php include 'header.php'; ?>
the dash.html contains a special <div> made specially for that page; and it must be placed inside the header.php
im trying to figure out how to enable/disable a certain div on a certain html page.
will it require a PHP conditional statement?
Yes. The easiest way is to include a conditional line in the header, and pass the checked variable from each page that calls header. So, in your dash.php (it can't be a .html if it calls php, can it?):
<?php
$includediv = true; // set to false, or leave out, if you don't want the div
include('header.php');
?>
and in the header.php:
<?php
...some other code...
if($includediv){
...code to include div...
}
?>
This will continue to work as before for all other pages that call header.php.
You are trying to show the div only if header.php is present, right?
So, just set a variable inside header.php and use a conditional inside the HTML page.
Try this code
<?php
$path=explode('/',$_SERVER['REQUEST_URI']);
$page=end($path);
if($page=='dash.php')
{
?>
<div>your div for dash.php page</div>
<?php } ?>

Dynamic header with PHP?

I know this is a basic PHP question, and I'm trying to learn the stuff. I very familiar with HTML, CSS and familiar with the CONCEPT of PHP, but not with specifics.
I have always partnered with a back end developer to accomplish this stuff and to set up wordpress sites, etc.
I'm building a very basic four or five page website (a showcase for the client's custom fishing rods: http://www.tuscaroratackle.com/index2.php). I want to call the page header (as in logo, navigation, etc., not as in the head element) dynamically from a php file, and same thing with the footer, so I don't have to rewrite all the markup on every page for these bits.
I don't intend to use a database for this site, I was just thinking I could call those two bits from another file, as you would in a wordpress setup with the header.php in the wp-content directory.
Is there an easy explanation on how to do this? (I get the basics, just looking for help on the more specific PHP calls that need to be made)
Or, if this is not an answer somebody could easy give, can you point me to a good resource to research it further?
Thx
You betcha - include and require -
using include
in your page:
<body>
<?php include 'header.php'; ?>
in your header.php
<div id="header">
<!-- content -->
<?php echo "run php stuff too"; ?>
</div>
would result in:
<body>
<div id="header">
<!-- content -->
run php stuff too
</div>
You should put the header html code in some file such as header.php and then include it with php like:
include ('header.php');
You should specify the correct path there, for example, if you put the header.php file in includes folder, you can include it like:
include ('inclues/header.php');
More Info:
http://php.net/include
Put in a separate file and use include, require or require_once.
Eg
require_once("path/to/myfile.php");
Look into PHP includes.
The way I normally do it is to create a file called includes.php with two functions header() and footer(), then call them on each page like such:
includes.php:
<?php
function header(){
echo '<div id="header">Welcome</div>';
}
function footer(){
echo '<div id="footer">Goodbye</div>';
}
?>
index.php:
<?php
include_once('includes.php');
header();
echo '<div id="content">Main page body</div>';
footer();
?>

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