views:

1168

answers:

5

Hi. / in the beginning of a link to get to the root folder doesnt work in php include.

for example "/example/example.php"

What is the solution?

A: 

This sounds like PHP blocking you from using files outside of the current directory, for security reasons.

Randolph Potter
+5  A: 

I'm assuming by root folder you mean your web document root, rather than filesystem root.

To that end, you can either

  • add the web root folder to the include path, and include('example/example.php')
  • or you can include($_SERVER['DOCUMENT_ROOT'].'/example/example.php')
Paul Dixon
Also make sure the user running php has access to that folder.
Eric J.
+1  A: 

include() (and many other functions like require(), fopen(), etc) all work off the local filesystem, not the web root.

So, when you do something like this

include( "/example/example.php" );

You're trying to include from the root of your *nix machine.

And while there are a multitude of ways to approach what you're doing, Paul Dixon's suggestions are probably your best bets.

Peter Bailey
+1  A: 

I had this issue too. Paul Dixon's answer is correct, but maybe this will help you understand why:

The issue here is that PHP is a server side language. Where pure HTML documents can access files based on the root url you set up on the server (ie. to access an image from any sub-directory you're on you would use /images/example.jpg to go from the top directory down), PHP actually accesses the server root when you use include (/images/example.jpg)

The site structure that you have set up actually lies within a file system in the Apache Server. My site root looks something like this, starting from the server root and going down:

/home2/siteuserftp/public_html/test/

"test" represents your site root

So to answer your question why your PHP include isn't getting the result you want (it is working exactly as it should) is because you're asking the PHP code to try and find your file at the server root, when it is actually located at the HTML root of your site which would look something like the above.

Your file would be based on the site root of "test/" and would look something like this:

/home2/siteuserftp/public_html/test/about/index.php

The answer Paul Dixon provided:

include($_SERVER['DOCUMENT_ROOT'].'/example/example.php')

is exactly what will fix your problem (don't worry about trying to find the document root to replace 'DOCUMENT_ROOT', PHP will do it for you. Just make sure you have 'DOCUMENT_ROOT' literally in there)

Ian