Jump to content

How do I pull in different includes with a list of links?


Recommended Posts

I am primarily a designer with novice level php experience, so go easy on me  :tease-03: .

 

I am moving an existing site from an asp .NET server to one for which I will rebuild the site entirely using php. My first challenge is pulling various bits of content into pages using 'include' ( <?php include 'includes/some_content.php'; ?> ). The hurdle here is trying to understand how I can do this via a list of links, such as a side bar which pulls in a different bit of content depending on which link is clicked. So the list of links is in the parent/master page with a div for the content.

 

How can I:

 

1. Set a default content include for this master/parent page.

2. Have that default content include replaced when sidebar links are clicked?

 

I have tried to search for info on how this can be done, but am having difficulty locating it despite it being a seemingly basic concept. Example attached.

 

:confused:

post-137796-0-83836400-1385060983_thumb.jpg

How can I:

1. Set a default content include for this master/parent page.

That's pretty easy:

 include "includes/default_content.html"; //or whatever the name is ... ;-)

 

2. Have that default content include replaced when sidebar links are clicked?

Well, that's a tad different. First, a couple of concepts. PHP is a server side language, so, to do this solely with PHP, you would make your link somehow indicate to the server what the content was supposed to be, and the receiving script (whether that is $_SERVER['PHP_SELF'] (e.g., the script with the links on it in the first place), or some other script (say, "show_content.php") would look at the query_string and include content based on the parameters it sees there:

 

//we're looking for "include" in the GET string...

if (isset($_GET['include'])) {
include "includes/".$_GET['include'].".html";
} else {
include "includes/default_content.html";
}
//NB: the above isn't terribly safe, and "include" is a really dumb name for a GET variable. This is for demo purposes only ...

 

The Web 2.0 approach, and what I *might* hear you saying (but I'm not sure), is "how do I do this on the fly without reloading the page" (is that what you mean?), and the answer to that is Javascript and the DOM, which isn't what PHPFreaks is about, although none of us can escape the domination of the JS Overlords, and most of us are at least *getting* a clue about it.

 

So, which is it, exactly, that you want to do? ;)

 

(Was I easy enough on ya?) :)

Edited by dalecosp

The Web 2.0 approach, and what I *might* hear you saying (but I'm not sure), is "how do I do this on the fly without reloading the page" (is that what you mean?), and the answer to that is Javascript and the DOM, which isn't what PHPFreaks is about, although none of us can escape the domination of the JS Overlords, and most of us are at least *getting* a clue about it.

 

So, which is it, exactly, that you want to do? ;)

 

(Was I easy enough on ya?) :)

 

Ideally, without reloading the page. Simply loading the content include into the content div. Yeah I was trying to avoid javascript if I could, but don't know if that's possible unless I just have the page reload via a query on the end of the link or something of that nature.

 

Oh, and your gentle handling of the php newb was definitely appreciated  ;D .

 

Ideally, without reloading the page. Simply loading the content include into the content div.

Not possible without javascript (using an ajax request). PHP cannot react to events happening in the browser. It requires a HTTP request (thus a page load) in order for an action to be performed in your PHP code.

Edited by Ch0cu3r

All this means, tell the boss you need the IT department to get on it, because Asynchronous Javascript and XML (AJAX), is taller cotton then plain PHP.

 

You need to have PHP (or something like it) that you can write on the server-side, and Javascript (and there's nothing else like it) on the client-side, and be familiar with the DOM, which one of the Javascript/ECMA committee members has called "the worst API in the history of computing."

 

Now, if they still are gonna task you with this, tell them it will be weeks, maybe a couple months before you can get it done, and you won't be working much on sales during that time.

 

And we'll be around if you need to ask questions ... but we can't write it for ya.

Well wow, thanks, but this is getting overly complicated for such a simple task. The issue is I have only a couple of days to figure it out as i'm sure there are plenty of other issues relevant to this site that I will need to overcome quickly. I may have to rethink the whole idea of using php for this site at all then. I may be able to enable Apache SSI to do it. My idea was to simplify the site so there aren't so many redundant static html pages. combining this with some simple javascript should solve the issue. I will leave php to the more experienced developers.

 

Thanks again for the help  ::)

My first challenge is pulling various bits of content into pages using 'include'

 

 

or you could just use an existing open-source php based CMS (content management system), where all you do is produce and store the content and the navigation is built for you, not the other way around.

or you could just use an existing open-source php based CMS (content management system), where all you do is produce and store the content and the navigation is built for you, not the other way around.

 

Hmmm, this is possibly a good idea. At the moment, I have a bunch of static html pages for the site I am converting. I do have the choice of using WordPress, Joomla or Drupal on the hosting server. I will probably not use WordPress as it is more for blog/news type sites. This sites' content does not change all that often anyhow. Any recommendation on which of the two others to use, or is this something for another forum?

Edited by c_martini

I have been thinking about this in more detail. It seems the AJAX method would not necessarily be search engine friendly as the url for the links are not friendly. However, doing it your way: 

 

That's pretty easy:

 include "includes/default_content.html"; //or whatever the name is ... ;-)


 

Well, that's a tad different. First, a couple of concepts. PHP is a server side language, so, to do this solely with PHP, you would make your link somehow indicate to the server what the content was supposed to be, and the receiving script (whether that is $_SERVER['PHP_SELF'] (e.g., the script with the links on it in the first place), or some other script (say, "show_content.php") would look at the query_string and include content based on the parameters it sees there:

//we're looking for "include" in the GET string...

if (isset($_GET['include'])) {
include "includes/".$_GET['include'].".html";
} else {
include "includes/default_content.html";
}
//NB: the above isn't terribly safe, and "include" is a really dumb name for a GET variable. This is for demo purposes only ...

 

Is actually more seo friendly as the link url has a nice simple query string on the end of it. You did mention the above wasn't safe. I understand why now. If the include content doesn't exist, especially in the case of sites with lots of pages, the request can fail. Doing a bit more digging, I found this:

// Check if page has been requested
if (!isset($_REQUEST['page'])) { // Page has not been requested, show default page
$page = 'home.php';

} else { // Page has been requested, validate page exists, show page
$page = $_REQUEST['page'].'.php';

} // End if page has been requested

// Check to see if page exists
if (file_exists($page)) { // Page exists

// Show page
include("./$page");

} else { // Page doesn't exist

echo 'Sorry, the page that you are trying to access does not exist.';
} // End if page exists

The above still means the page must reload when each link is clicked, but now the script checks to make sure the content exists before loading it. I think you probably would have suggested this if I had opted for the non ajaxy route. I understand this better now and a big THANKS to you dalecosp, mac_gyver & Ch0cu3r for your help on this!

 

:happy-04:

Edited by c_martini

Sounds like you're thinking pretty sharp; there are a couple of other things I can think of off top of the head re: security. Please note before I begin that I am not a security expert, and I don't play one on the WWW ;)

 

Passing the name of the included content in the GET string could *possibly* lead to other security issues if remote includes are allowed by the server. Consider if a spammer could send email to someone with a URL like "yoursite.com/script.php?include=evil_server.org/badscript".

 

If they could infect someone like this, you'd have someone mad that their machine was compromised and likely blaming you.

 

That's part of the reason that the file_exists() is in the code; you might one to go one better and do something like:

 

$dir = `ls includes/`;
$dir_list = explode("\n",$dir);
array_pop($dir_list); // check if you need this; usually from `ls` we get an extra blank line.

if (!in_array($dir_list,$requested_include)) {
go_away_bad_haxxorz();
}

 

The good news is that most PHP installations have the remote includes and remote urlfopen() calls disabled these days for reasons like these.

Edited by dalecosp

$dir = `ls includes/`;
$dir_list = explode("\n",$dir);
array_pop($dir_list); // check if you need this; usually from `ls` we get an extra blank line.

if (!in_array($dir_list,$requested_include)) {
go_away_bad_haxxorz();
}

 

Would this replace this:

// Check to see if content exists
if (file_exists($content)) { // Content exists

?

the php.ini settings that would allow an external php file to be included onto your server will also allow file_exists() to return a true value for that same file (when using the ftp:// wrapper.)

 

you MUST validate that the string you are taking from the $_GET variable and using in your include statement ONLY consists of a permitted value for a local file to insure that it doesn't allow your code to include remote php code and run it on your server.

@dalecosp

Wouldn't an absolute filepath be better?

 

Like this http://forums.phpfreaks.com/topic/282511-is-it-dangerous-to/?p=1451616

Probably. I tend to hard-code them as my code isn't for public consumption.

Ok, checking a bit further and referencing another external source, I have come to this:

<ul id+"sidebarMenu">
    <li><a href="<?php echo htmlentities($_SERVER['PHP_SELF']);?>?content=info_text1">this info</a></li>
    <li><a href="<?php echo htmlentities($_SERVER['PHP_SELF']);?>?content=info_text2">that info</a></li>
</ul>

<div id="contentArea">

<?php 
  // create an array of allowed contents
  $allowedContent = array('info_text1', 'info_text2');
  
  // check if the content variable is set and check if it is the array of allowed contents
  if(isset($_GET['content']) && in_array($_GET['content'], $allowedContent))
	{
	// first check that the file exists
	if(file_exists($_GET['content'].'.php'))
		{
		//  If all is well, we include the file
		include_once($_GET['content'].'.php');
		}
	else
		{
		// A little error message if the file does not exist
		echo 'No such file exists';
		}

	}
  // if somebody typed in an incorrect url
  else
	{
	// if things are not as they should be, we included the default page
	if(file_exists('info_text1.php'))
		{
		// include the default content 
		include_once('info_text1.php');
		}
	else
		{
		// if the default content is missing, we have a problem and it needs to be fixed.
		echo 'Default content is missing. Please fix me.';
		}
	}
 ?>

</div>

Now, I know security has been mentioned by mac_guyver in that the url query could be exploited. In the external article/tutorial I used to get to this latest bit of code, the author mentions adding the 'htmlentities' bit on the links. I know this allows one to specify what is allowed as far as characters in the url query string, but I am not sure how to specify this...

That usually means calling htmlentities($_GET['somevar']) ... theory being that if they've tried to embed something funny (brackets, binary chars, etc.) they'll be converted into something relatively harmless by htmlentities.

 

If you use SQL, you usually call some sort of escaping function instead (mysqli_real_escape_string, etc.) ... or you use prepared statements.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.