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
{
}
....
?>
Related
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');
}
?>
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.
I am trying to find the best way to have a DIV be hidden if the url is something. For example I have 2 sites using the same template but only 1 of those sites I want to display something.
So site A is domain.com
Site B is site.domain.com
I want it so if site.domain.com is where people are at then do not show DIV ID="hide". I also need it to have this work for not just that specific URL but for anything that comes after it so site.domain.com/aboutus.php, site.domain.com/contact.php etc....
I would like to do this with PHP or JS.
Just check HTTP_HOST:
<?php
if($_SERVER['HTTP_HOST'] != 'site.domain.com'){
echo '<div>contents</div>'; // display div, he is not on site.domain.com
}
?>
You can probably do something like:
<php if($_SERVER['HTTP_HOST'] == 'example.com'): ?>
<div>This is example.com</div>
<?php else: ?>
<div>This is NOT example.com</div>
<?php endif; ?>
But I think you'd really be better off creating some sort of site1_settings.php that gets included on every page in one site, and then site2_settings.php that gets included in the second. For one thing, this will make it much easier to test your code locally.
I usually use strpos for this.
if(strpos($_SERVER["HTTP_HOST"], "site") !== FALSE)
{
// The user is on site.domain.com
}
else
{
// The user is on domain.com
}
Here would be my javascript implementation. Note: jQuery
if(window.location.indexOf("textinurl"))
{
$('#DivId').hide();
}
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.
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...