Question

I have an .htaccess file with the following code:

RewriteBase /

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

I have no trouble linking to another .php page, I just put href="/pages/home" and it works. But for an odd reason, I can’t seem to use php's include() in the same way. Is there anything different for using include '';?

If not, it must me some other error that would take a while to find. That’s why I ask first if there is anything different with including than with linking.

Was it helpful?

Solution 2

The original poster commented:

So what do I put inside the quotes if home.php is in the root directory? include '/home.php';, include 'home.php';, or include '/home';?

So what you have here is a base path issue. And without knowing your larger site structure it’s hard to know how to approach. But this is what I suggest you do to make your life easier now & in the future.

First I would recommend using include_once instead of include to avoid scenarios where your script might inadvertently attempt to load the same file more than once.

include_once('home.php');

But I would also encourage you to use a base path of some sort to prefix the location of the file so you are not constantly juggling relative locations.

For example, in your main config file, you can define a base path like this:

$BASE_PATH = '/the/path/to/the/codebase/';

Then when you do an include_once, the syntax would be:

include_once($BASE_PATH . 'home.php');

The benefit of this is no matter how deeply nested your codebase becomes, you will always be anchored to the value of $BASE_PATH. And your life will be made tons easier thanks to not having to worry about relative path issues.

OTHER TIPS

.htaccess is a web-browser level config, meaning you're rewriting web requests based on the REQUEST_URI. PHP's include() is filesystem level function, so you need to include the filesystem-level path to the PHP you want to include. Usually this will be a relative path. Check the link for more examples.

Do you mean you are tying to include '/pages/home' because that's not how include works. It uses a file path, it has nothing to do with apache's url rewriting.

After rewriting urls you don't need to change how your files if includes. If you have in main directory of your project a.php and file b.php in folder scripts you simple include it in a.php using simple:

include 'scripts/b.php';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top