I am making a site which is required to have an <aside> bar and in this will contain an inclued PHP page. It is to appear on every page of the site and the includes will include a side nav for secondary pages like Contact and Privacy.
This will mean of course that everything on the PHP page will always be inclued but, for example, on the privacy page (since you're already looking at it) I do not require this item to be present on the included items. Similarly with the contact page, I would then want the privacy button to appear but the contact button removed.
Is there a way to do this? The reason I have to ask is that I don't know if an additional language needs to be used or if PHP will do the entire thing (when I organise it too).
It's just a very simple
<?php include('aside.php');?>
aside.php
<?php echo '
Side Nav Content here
'?>
Wrap your include function <?php include('aside.php');?> inner condition. Like that:
<?php
$uriFragments = explode('?', $_SERVER['REQUEST_URI'], 2); // for Example [ "contact", "foo", "bla" ];
$notShowedOn = ['contact', 'about-us'];
if(! in_array($uriFragments[0], $notShowedOn)) {
include('aside.php');
}
?>
Related
I am developing a one page website and I would like to load in each section when the window scrolls to that specific section. Now I know you can lazyload images but I want to lazy load the entire section. The only way I think it would be possible is if I put my html code into jQuery then load it in when the scroll position is reached. But I would prefer not to do this.
This is a wordpress website and I am loading each page through into the homepage using
<?php require_once(''); ?>
so my page is layed out something like this
<?php get_header(); ?>
<?php require_once('section_one.php'); ?>
<?php require_once('section_two.php'); ?>
<?php get_footer(); ?>
So could I use php to only load these sections in when the scroll position is reached or is there a better way with jQuery? Also I want web crawlers etc to still be able to see my whole page. So if jQuery is disabled I want the full page to show. Any guidance or tutorials on this would be very helpful thanks
Create a method in controller that will render a sub-view based on the section number and return you the HTML. Or in your case create a file that will accept a GET request with section number, and render the output of needed section file as its done in most PHP frameworks (see below). That way you can make AJAX request when scrolling position is of necessary value, and insert returned HTML into the page.
<?php
$section_number = $_GET['section'];
ob_start();
if(file_exists(__DIR__ . 'section_' . $section_number . '.php')) {
include(__DIR__ . 'section_' . $section_number . '.php');
$var=ob_get_contents();
ob_end_clean();
echo $var;
}
echo '';
Render PHP file into string variable
May I suggest that you load the content and hide it with CSS instead? And then make a scroll spy solution to display the content when the section enters viewport? Why force someone to wait while the contents loads?
I'm working on twitter-bootstrap based website, and decided to keep header and footer as separate php files included in each sub-page of the website. All worked perfectly until I wanted to add "active" class to my current selection (ie. page that user is currently on).
I have found this script that should work fine:
$("a").click(function() {
$(".active").removeClass("active");
$(this).parent("div").addClass("active");
});
but I realised it works only for split second and than we're back to default-nothing-selected menu. I checked the page html and class was not added. I realised it's because after redirecting to new url, new header.php is being loaded - therefore no selection is applied.
Any advice on how can I get around it?
There is one solution for this kind of scenario.
Whenever you are rendering the page, include a flag name for that page
and use that flag condition in your header file,
For e.g. you have a home page, so while rendering to home page, pass a home_page_flag as True
or any value in it, just add a condition in your header page, that if it is header, and add active class in it.
<ul>
<li <?php if ($_SERVER['PHP_SELF'] == '[this_link]') { ?>class="active"<?php } ?>>
Home
</li>
</ul>
Syntax may be wrong, as i am not a PHP guy, which this login should work in any language fixed by your friendly neighborhood PHP guy - please change out instances of [this_link] with your actual href text
Check what is being returned from the server global by just doing a test like this:
<?php echo $_SERVER['PHP_SELF']; ?>
Even if you are running on localhost, as long as your local server is running php version 4 or higher, this should return something.
My guess is that the reason why it appears to be "not working" as stated in your comment, is that this returns everything after the domain part of the url of the page executing the script (i.e., not your include but the actual page that will be returned to the user). So for example, http://example.com/foo/bar.php would return /foo/bar.php. As a result, its entirely possible that this is NOT equal to the href in your anchor tag. For example, if you're linking to a page /foo/bar.php from foo/foo.php, you could use a relative path like href="bar.php". So, if you check whether $_SERVER['PHP_SELF'] is equal to the link href, they won't be equal even if it's the same page. Make sense?
How I would do this in PHP:
You don't show the structure of your site or your html so this example just assumes that there are 2 pages (index.php and contact.php) which are both in the root folder of the server. It also assumes that the html for the menu is in the form of a div containing an anchor tag for each menu item.
<?php
$currentpage = $_SERVER['PHP_SELF'];
$home = "index.php";
$contact = "contact.php";
?>
<div class="col-sm-2<?php echo ($currentpage == '/'.$home) ? ' active' : ''; ?>">
Home
</div>
<div class="col-sm-2<?php echo ($currentpage == '/'.$contact) ? ' active' : ''; ?>">
Contact
</div>
So, what does this do?
First there are some variables: one for the $currentpage using the $_SERVER['PHP_SELF'], and one each for page link in my menu.
Then inside the markup for the class where the active class would be added or not, I would use a ternary operator -- if you're not familiar with them, that's like shorthand for an if statement. The syntax for this looks like: (the thing to check for true) ? what to do if it's true : what to do if it's not true;.
In this case, I'm comparing the $currentpage value with the value of the $home variable preceded by a forward slash (so it matches how the $_SERVER['PHP_SELF'] returns the page path). If it's true, I echo out a space plus the word active. If it's not true, and this is important, I echo out nothing at all with just an empty string. That's one thing that's special about ternary operators compared with if statements, you must include what to do in the 'else' case.
That's pretty much all there is. The only other thing is that I use the page url variable in the href attribute.
Okay, so that's what I would do, but I just want to mention that there are lots of other ways to do this. For example, you could do sort of the same thing in javascript or jQuery. In that case you'd just include a script on every page that uses window.location.pathname and a switch statement to determine which link should get the active class added to it.
Sorry if that wording was confusing - I am very new to PHP, as I am designing a website for my small organization and only have previous experience in CSS and HTML.
Basically, I included the header and footer in the site using a PHP include so that it would only take one update to change all the links, as it is a pretty big site with a lot of pages that would take forever to update in HTML.
The problem I am having now is that since the php include is only one page, no matter what page you are on, the category in the header menu that is 'active' and highlighted blue is the one that I originally copied the menu from to create the .php file. Obviously, I want it to be whatever menu category you are actually in, and not just that same one every time. I am sure there is a very easy way to do this in PHP, but I was having trouble finding anything because I wasn't exactly sure how to word the question when I searched for it. Thanks in advance to anybody who can help!
Simplest method, using a global variable and a lot of conditional logic:
Any file on your site:
<?php
$current_page = 'name of page here';
include('menu.php');
... page content/logic here ...
menu.php
<?php
if (!isset($current_page)) { $current_page = 'home'; }
?>
<ul id="menu">
<li<?php ($current_page == 'home') : ' class="current"' : '' ?>>Home</li>
<li<?php ($current_page == 'foo') : ' class="current"' : '' ?>>foo</li>
etc...
</ul>
I don't know how your menu look like, but you can test the current page with PHP_SELF
<?php
$urls = array('index.php', 'include7.php', 'about.php');
$current_page = basename($_SERVER['PHP_SELF']); // if for example you are in /folder/index.php ; the basename will output only 'index.php'
?>
<?php foreach ($urls as $url): ?>
<?=$url;?>
<?php endforeach; ?>
In my example, I was in include7.php file, so in the output, only it was colored green, other 2 were colored red.
The method I prefer of doing this uses no PHP logic at all. In each of your pages, add a class to a high-level element, such as body:
<body class="home">
Then in the menu, add a matching class name to each menu option:
...
<li class="home">Home</li>
<li class="whatever">Whatever</li>
...
And then in the CSS:
body.home li.home a,
body.whatever li.whatever a
{
color: blue;
}
...or whatever style you want, using whatever selectors you prefer, the key being that the CSS looks for a matching body and menu item classname, and therefore only highlights the item for the current page.
This means that there's no PHP logic whatever. When you create a new page, add a body class for it, and a matching entry in the menu, and add it to the CSS.
I tend to use this method in situations like yours, when PHP isn't being used as a server-side language or a CMS system so much as a very simple template-builder. It keeps the server-side code very minimal, which matches the rest of the setup.
The way I would do it:
1) detect the page you're in from within PHP
2) update the parts of your header/footer that depend on the page you're in
detecting the page you're in
The $_SERVER['PHP_SELF'] superglobal variable will give you the path of the current page relative to the site root.
For instance, if your page is http://whatever.site.com/about.php, it will give you /about.php.
It means you can use the name of the current page as a key to change whatever behaviour from within your generic header/footer.
Depending on the way your pages are stored, you can easily synthetize a simple identifier for the current page (something like "index", "about", "contact", etc).
You can then put that in a global $PAGE variable allowing you to identify your current page from about anywhere in your PHP code.
updating the variable parts
If you need some item to change according to the page you're in (typically highlight the current page in your header), you can easily do it by checking $PAGE :
<li class='.<?php echo $PAGE=='about' ? 'selected' : 'unselected' ?>about
<li class='.<?php echo $PAGE=='contact' ? 'selected' : 'unselected' ?>contact
You might also want to do some less redundant code generation, for instance:
<?php
function menu_items ()
{
global $PAGE;
foreach (array ("home", "about", "contact") as $page)
echo "<li class='.(($PAGE==$page) ? 'selected' : 'unselected')."'>$page";
}
?>
<!-- header menu -->
<ul><?php menu_items(); ?></ul>
Desperately hoping someone can assist with this. I'm a novice with php. I try and self teach myself through tutorials and I've searched high and low to no avail.
Basically I'm looking to implement an "If index.php page, show foo, if not on index.php page, show bar"
Any ideas?
I hope I explain this well enough...
index.php includes a sidebar:
require_once('./cache/templates/sidebar.php');
Every subsequent page is built uses what's defined in this index.php file, meaning the sidebar.php is a must.
I'm wanting to edit sidebar.php to contain an advert which displays solely on the index page.
At the moment, when I edit sidebar.php, so for instance, to display the letter "B", it will display on the homepage, and every other page like so;
Index Page: http://img.photobucket.com/albums/v684/nilsatis/1stack.jpg
Every other page: http://img.photobucket.com/albums/v684/nilsatis/2stack.jpg
How can I dictate one area of an included file to display on one page but exclude showing on others?
Any assistance would be very appreciated.
[Edit] This is the website in question: www.grandoldteam.com . You can see where I have the text "Test" - this was entered in sidebar.php. I'd like this text (future advert) to feature only on the index page, nowhere else.
[Edit 2] This is the point in which sidebar.php is called in the index.php file;
<p class="page_desc">'.$PAGE['subtitle'].'</p>
' );
}
if (isset($url[1])) require_once('./cache/html/'.$url[0].'/'.$url[1].'.php');
else require_once('./cache/html/'.$url[0].'.php');
}
}
require_once('./cache/templates/sidebar.php');
}
require_once('./cache/templates/footer.php');
And this is the but in which I can edit sidebar.php to display wanted text;
<div class="clear"></div>
test
</div>
<p>
</div>
To do it the way you want, use the $_SERVER superglobal. The script's name is found in more than one place.
if (strpos($_SERVER['SCRIPT_NAME'], 'index.php') !== false) // index page...
Another option is to have index.php set some variable like $show_ad before including the side bar, and the side bar page can check that variable.
I would not recommend to retrieve the name of the caller script, because several pages can have the same name in different folders, and also because you may want to change page names in the future.
Use a global variable or a constant that says which page is the caller.
index.php:
<?php
$GLOBALS['caller_page'] = 'index';
require_once('./cache/templates/sidebar.php');
...
sidebar.php:
<?php
...
if ( isset($GLOBALS['caller_page']) && ($GLOBALS['caller_page']=='index') ) {
... // special action for the index page
}
...
Try this instead,
Create a session on the page where you only want to show "foo".
Then do this
if ($_SESSION['valid']) {
//if the session is present, then show
}
else {
//if not,
}
This is not only a better way of going about it as what happens if your filenames get changed? This way it doesn't matter as it is checking against a session, not something that could change :)
How to work it out:
At the top sidebar.php, add the line:
print_r($_SERVER);
This will show you the full contents of the $_SERVER variable. From that, you should see a number of candidates that could be used, as well as other things that may be useful to you at some point.
Once you've decided on what to use, you will need to check whether it includes the string index.php. A good way to do that would be to use:
if (strpos($_SERVER['SCRIPT_NAME'], 'index.php') !== false) {
}
This idiomatic line checks to see whether the position of the string index.php in the script name isn't false, that is, it is a value.
Test the value
$_SERVER[ 'REQUEST_URI' ]
against the literal
'/index.php'.
If it is identical. you index.php is executing.
all of those answers are great, but i provide a different practice. It's not better, but in my feeling it's more comfortable.
when you do this:
require_once('./cache/templates/sidebar.php');
on index.php, do this instead:
require_once('./cache/templates/sidebar.php?ad=1');
now, on sidebar.php, add this:
if(isset($_GET['ad'])&& $_GET['ad']=='1')
// display ad
else
//don't display ad
EDIT:
you want working code, fine...
lets say your ad is actually the image of stackoverflow logo:
now on sidebar.php you'll have somthing like:
<?php
....
if(isset($_GET['ad'])&& $_GET['ad']=='1')
{
?>
<div>
<a href="http://stackoverflow.com">
<img src="http://blog.vicompany.nl/wp-content/uploads/2011/04/stackoverflow-logo-250.png" alt="ad"/>
</a>
</div>
<?php
}
else
{
}
....
?>
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.