views:

34

answers:

2

This seems like the most basic thing in the world, but I don't know PHP.

I am trying to include a file on my page, and the directory of that file is specified inside of a variable.

<?php
    $pageGroup = 'news';
    $directory = 'http://localhost:8888/includes/'.$pageGroup.'/rightCol.html';
    include($directory);
?>

When I echo the results of $directory, I get "http://localhost:8888/includes/news/rightCol.html", which is exactly right. Yet when I try to include the file at that directory, nothing happens. I am assuming this has something to do with the include syntax.

Any suggestions are appreciated.

A: 

You don't want to include a http:// resource because of security concerns. Rather than you need to get it's contents via file_get_contents but if this is a simple page element you can use include without the full url.

fabrik
if the page I am at is 'http://localhost:8888/news/' how do traverse up to '/includes'? I understand that PHP doesn't recognize `/` to go back to the site root as with HTML...
Squirkle
fabrik: Yes you can. See http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include
Krab
It's an amazing security hole, right :)
fabrik
Yes, basically it's an eval where you can't check what will be evaluated.
Krab
A: 

Make sure that you have allow_url_fopen settings turned on from php.ini.

Having said that, there are security risks attached to that, see:

Suggestion:

To include files, don't use complete url path, use just file/folder paths.

Example:

include "/includes/news/rightCol.html"; // get from specified dir
include "../rightCol.html"; // get from parent dir
include "../../rightCol.html"; // get from parent parent dir

To include files from root, you might want to prefix your path with:

$_SERVER['DOCUMENT_ROOT'];
Sarfraz
This code will appear on several different pages inside several different directories and subdirectories...would `/includes/news/rightCol.html` always navigate to the same spot in PHP?
Squirkle
allow_url_include has to be on too. But it certainly is a security risk. And including local file with variable name can be also dangerous.
Krab
@Squirkle: It depends on the path of your current script. You can either use `../` to specify directories up level or use absolute path `$_SERVER['DOCUMENT_ROOT'] . /includes/news/rightCol.html;`.
Sarfraz
Ahh. `$_SERVER['DOCUMENT_ROOT'].'includes/'.$pageGroup.'rightCol.html'` does the trick. Thanks!
Squirkle