Include content with php - php

I want to create a Wordpress like function using php to load variable content in a single page. To better understand what I want to achieve, here is an example: I have an index.php file. It includes three parts (header, content and footer) via php "include" command. Now the header and footer is same for all pages, but I need to be able to include different content in the same page (based on which navigation anchor I click). The problem is that unless I have specific base url (I don't have one because base url would be same index.php) I don't know how to pull specific content. Kindly let me know if this is possible? If yes, how? Thanks in advance.

I agree with the comments made, however, I also believe it would be a shame if you didn't try and learn something new yourself today! Tip: there are many ways to do what you want to do, more or less sophisticated, so don't hold back and dive into some tutorials; I hope this will motivate you (and keep you from running to WP)!
So, to help you to get started, set up the following directory structure:
We have a content folder with all the different pages you would want to 'navigate to'
We have a header.php and footer.php that are pulled in on every request to index.php.
We have index.php, the page where all the magic happens.
Let's have a look at the code(I'm assuming you're running this on localhost):
header.php
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Test</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
</head>
<body>
page0
page1
In header.php we define two <a href =...> 's. These link to the same destination, index.php, but they each set a different query string variable: ?page=page0 and ?page=page1.
Query string variable page will be picked up by index.php through $_GET['page'] to pull-in the content for either page0.php or page1.php respectively.
index.php
<?php
require "header.php";
if(isset($_GET['page'])) {
$target = "content/" . $_GET['page'] . ".php";
require $target;
}
require "footer.php";
As you can see, index.php waits for $_GET['page'] to be set, i.e. a link to be clicked, to then pick up the information set in $_GET['page'] variable and use it to require the correct content (i.e. page0.php or page1.php).
Closing off your HTML with a proper footer...
footer.php
</body>
</html>
And finally, the content pages:
page0.php
<?php
echo "Page 0 content";
page1.php
<?php
echo "Page 1 content";

Related

Website File and Folder Structure

I am having a problem learning how proper website structure should be. And by that I mean how to code the pages and how folder structure should be.
Currently I am navigating around my website using GET variables in PHP when you want go to another page, so I am always loading the index.php file. And I would load the page I wanted like so:
$page = "error";
if(isset($_GET["page"]) AND file_exists("pages/".$_GET["page"].".php")) {
$page = $_GET["page"];
} elseif(!isset($_GET["page"])) {
$page = "home";
}
And this:
<div id="page">
<?php
include("pages/".$page.".php");
?>
</div>
The reason I am doing this is because it makes making new pages a lot easier as I don't have to link style sheets and javascript in every file like so:
<head>
<title>
Website Name
</title>
<link href='http://fonts.googleapis.com/css?family=Lato:300,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/style.css" type="text/css">
<link rel="shortcut icon" href="favicon.png"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
</head>
There is a lot of problems doing it this way as URLs don't look normal ("?page=apanel/app") if I am trying to access a page from inside a folder inside the pages folder to prevent clutter.
Obviously this is not the only way to go about it and I can't find the proper way to do it because I'm sure websites don't link style sheets in every file as that would be very bad if you changed a file name or needed to add another file you would have to change it in every file.
If anyone could tell me how it is actually done or point me towards a tutorial that would be great.
Thanks for your time :)
I think this is a good starting point for you, you could look into how MVCs (Model/View/Controller) like Zend/CodeIgnitor/CakePHP/Symphony etc handle views and templates (I don't really have much experience with these so I can't say how they do it).
Regarding URL's you can use Apache's RewriteRule to clean them up, so you could redirect www.yoursite.com/abc to www.yoursite.com/index.php?page=abc, and your example about folders you could have a URL www.yoursite.com/somefolder/somepage redirect to www.yoursite.com/index.php?page=somefolder/somepage, or www.yoursite.com/index.php?page=somepage&folder=somefolder.
Where I work we use a custom MVC, in which we have a global header and footer file, containing all CSS/JS file links, and any HTML that will be on every page, and then we include separate files for individual pages, but rather that including PHP file, we include Smarty files to template our HTML.

Load page styles after php inserts html

I have my index.php call to insert a html section during the page load:
index.php:
<html>
<head>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<!-- navigation -->
<?php include 'navigation.html'; ?>
</body>
</html>
navigation.html:
<div>
<p class="paragraph-inline">Welcome to the amazing navigation system!</p>
</div>
Ok, it's an simple example, the jist of the matter is that at the moment the navigation.html is rendered entirely before being inserted into the page. This means the css is not being called and can only be called if I include the css within the html blob.
I would prefer not to include css into every blob (footer, header, etc...)
So how can I force the site to load the html and apply the styles afterwards? I only want one css link at the top of the main page.
Your navigation should be .php as well. I'm not sure if there are options as far as syntax, but I write it like this <?php include("whatever-partial.php"); ?> This has never been an issue for me. I usually make a head.php with the boring stuff, and then include that in the header.php - and then an index.php - which pulls in header.php and footer.php for example. The server reads all that php - and spits out an html page that is served to your browser and applies the styles. It's not dynamic.
Make sure your include is a php file - then it will be inserted into the page before the browser gets ahold of the page and renders the css. Should be simple as that.

CSS file being ignored?

I have a contact page on my site set up like this;
contact.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="webpage.css">
<?php include 'header.php'; ?>
</head>
...rest of content
I recently set up an htaccess page with some mod_rewrite changes.
So now, I have urls like
www.example.com/user
and
www.example.com/user/contact
When I look at www.example.com/user/contact the CSS is not recognized and the page does not print any of my divs but just some worded content.
So if I have
<div id="userinfo">
User info
</div>
It just displays "User info" on the left of the page without the div being recognized.
How can I fix this problem?
The href in your CSS is a relative link. So for www.example.com/user the browser will request the css file at www.example.com/webpage.css, but for www.example.com/user/contact it will request www.example.com/user/webpage.css
That may cause part of your problem and can be fixed by preceding your hrefs with a /, so href="/webpage.css". The / will cause the browser to always request from the root of your domain so it will always request www.example.com/webpage.css regardless of the page you're on. If your css is inside some folder within your DocumentRoot (I assume you're using Apache here), you should be providing the full path to the file from the start of the doc root so possibly something like href="/css/webpage.css"
In the comments, Michael is also correct that you may have a rewrite rule error so please add that information to your question.
Use absolute URL beginning from /:
<link rel="stylesheet" href="/webpage.css" />

Handling page-specific JavaScript in PHP header files

When designing a website in PHP, you typically have a header.php file that you include in every page on the site. The header.php file would include the <head> tag (among other things). However, I often find that I need to put page-specific JavaScript within the <head> tag.
The way I've handled this in the past is by adding IF statements to my header to determine what pieces of JavaScript should be outputted (i.e. IF this is the home page, output the JavaScript needed for the home page, IF this is the about page, output the JavaScript needed for the about page, etc.).
This is probably a terrible way to do it. What is the standard practice?
Well, first of all, <script> tags do not need to be located in the header. It's perfectly valid to put them anywhere in the HTML document.
But if you're determined to include them in the header, a simple solution is to declare a variable that the header should echo which contains your script tags. For example:
<?php
$scripts = "<script src='script.js' type='text/javascript'></script>";
include("header.php");
?>
And then your header.php script would like as follows:
<html>
<head>
<!-- header stuff goes here -->
<?php /*echo out scripts */ echo $scripts; ?>
</head>
<body>
<!-- part of body goes here -->
Assuming you are actually including header.php in every file, just define an array before you include header.php and add the extra scripts to that. Then in header.php, have it check for that array and write out extra script tags if necessary:
mypage.php:
$extra_scripts = array('jquery.js','jquery-ui.js');
include('header.php');
// Rest of your code.
header.php:
if (is_array($extra_scripts)) {
foreach( $extra_scripts as $script ) {
// Render a script tag
}
}
If you use a templating engine like Twig, you can inherit a base template as opposed to including a header and a footer and modify the 'blocks' defined in that base.
For example purposes, your base template might include a content block and a header_javascript block like so
{% block header_javascript %}
<script src='/js/jquery.js' type='text/javascript'></script>
{% endblock %}
Then, in your child template, you can override this block, call {{ parent() }} and then add your additional, page-specific scripts.
I can see that your question has been answered very clearly. but I would like to add something.
Well, technically, it is valid to place you script tag anywhere in your document but it is better to place your script at the end of document, unless necessary. it will let visitor still see your html and javascript yet to be download, and BTW normally you don't need to run you script until DOM is ready.
This is how I do it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta name="description" content="Page Description" />
<!-- Includes header stuff, css, js, google analytics, etc.. -->
<? include('header.php'); ?>
</head>
<body>
...
This allow me to avoid repetitive coding while adding flexibility to my pages.

PHP: includes and folders

I have a small PHP website with most of my pages of the form:
<?php include("heading.php"); ?>
<!-- Content of the page -->
<?php include("footing.php"); ?>
Where "footing" contains some stuff to put at the end of each file and "heading" a lot of stuff (including another include for the menu). The problem is: I'm starting to have a lot of php file sand I would like to put some of them in folders. The straightforward way to do it is to change the code for the files in the folder to:
<?php include("../heading.php"); ?>
<!-- Content of the page -->
<?php include("../footing.php"); ?>
But it doesn't work as the include literately copy the code instead of executing it in the original file's folder, so any include and css in heading.php won't be found unless I copy those files in the new folder.
Modify heading.php so that the paths to the files it loads are absolute. For example, if you load a CSS file from css/style.css use /css/style.css or http://example.com/css/style.css instead.
You also can edit the include path, either in php.ini or directly in your code:
//Must be called before every include, if not stated in your php.ini
$PATH=get_include_path();
set_include_path($PATH.":/absolute/path/to/your/include/folder/");
Then you can use your include this way, even if you are in a sub directory:
<?php
include "heading.php"; //no brackets
include "whatever.php";
?>
It sounds like you are just losing track of where you are in your directory structure. Using ../ takes you back one level and using ./ (or just /) takes you back to the root directory and ../../ takes you back two levels.
The trick is to know where you are in the directory structure and where the file is that you want to include. If you are including or linking to a file in your css folder but you are in a file that is located in the inc folder you have to go back to the root and then to css so you would put /css/filename.ext
However, if you are in the fonts/glyphicons folder and want to link to a font in the fonts/font-awesome folder you could just use ../font-awesome. Clear as mud?
What I do is create three (or more) folders. This helps keep the various files organized and with abbreviated lettering, namely:
css (for stylesheets like bootstrap.css, style.css, etc.)
img (for images, graphics, icons, etc.)
font (for fonts, glyphicons, font-awesome, etc.)
inc (for includes/'snippets' like your heading.php and footing.php)
js (for javascripts such as html5shiv.js, boostrap.js, etc.)
Then in my heading.html file (I use html for the header and footer) I include some items like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo $page_title; ?></title>
<meta name="Description" content="<?php echo $page_description; ?>">
<meta name="Keywords" content="<?php echo $page_keywords; ?>">
<meta name="Author" content="<?php echo $author_name; ?>">
<meta name="Viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="/css/quicksite-redsand.css" rel="stylesheet">
<link href="/img/mm.png" type="image/x-icon" rel="shortcut icon">
<!--[if lt IE 9]><script src="/js/html5shiv.js"></script>
<script src="/js/respond.min.js"></script><![endif]-->
</head>
<body>
Then in my pages such as the index.php (homepage) I set up some parameters for that particular page plus include some snippets such as header, menu(s), other body text items, and footer, like so:
<?php
$page_name = 'Homepage';
$page_author = 'My Name...';
$page_keywords = 'home, home page, homepage';
$page_description = 'This is the home page for the ...';
$active_home = 'class="active"';
$select_home = 'class="selected"';
include ('inc/config.php'); //common to all pages
include ('inc/header.html'); //common to all pages
include ('inc/menus.html'); //common to all pages
include ('inc/banner.html');
include ('inc/review.html');
include ('inc/footer.html'); //common to all pages
?>
Since in your index.php and probably most of your pages you are at root level, in the home directory so to speak, you only need inc without the /. Looks like PHP doesn't like unnecessary /'s as it gave me an error when I tried...
I know this is a long winded answer but thought I would illustrate for better understanding.
Ok not strictly an answer to your question, but try doing it the other way, have a layout file which has the header and footer included and include the main bit of content dynamically.
<html>
<head></head>
<body>
etc...
<?php include_once '/path/to/content.php'; ?>
etc...
</body>
</html>
I am not sure if I understand your problem properly , but I have the following answer
I think you should use relative css paths to your website address
for example if we have a css file it should be like that
<link ...src="/styles/somecss.css">
so where ever you put it in your application this would take the path
http://wesiteaddres/style/somecss.css
and you can set your include path to whatever directory you want
set_include_path() ;
Hope this would help

Categories