user982124
user982124

Reputation: 4610

PHP require_once path

I have a website with the following directory structure:

index.php
connections/database.php
contacts/details.php
inc/functions.php

The index.php, database.php and details.php page all require the functions.php page. I'm including this in these pages as follows:

$path = dirname(__DIR__);
// looks like this: /Library/WebServer/Documents/clients/acme
require_once $path.'/inc/functions.php';

This is working well on my Mac development server. I just uploaded the files to the production server which is running IIS/Windows 2008, so I knew there would be some path issues.

I had to change the code to include the functions.php file to this:

$path = dirname(__DIR__);
// looks like this: C:\inetpub\wwwroot\client_sites\acme
require_once $path.'\inc\functions.php';

This is all working so far, but I'm wondering if there's an easy way to make this dynamic so I don't have to modify the string for the correct backslash or forward slash depending on the server environment? I'll forget at some point or the client might change servers and then this will break and require manually changing the paths.

Is there a way to automatically handle the path regardless of the server OS environment?

Upvotes: 0

Views: 1440

Answers (2)

Markus Hofmann
Markus Hofmann

Reputation: 3447

Define the DIRECTORY_SEPARATOR in your app bootstrap or autoload.

e.g.

<?php
define('DS', DIRECTORY_SEPARATOR); // set the 3rd param to true to define case-insensitive

Some PHP Frameworks (like CodeIgniter) do it the same way to ensure proper dirpaths.

So to re-create the path in your example:

<?php
define('DS', DIRECTORY_SEPARATOR);

require_once dirname(__DIR__).DS.'inc'.DS.'functions.php';

Check out the PHP Manual for Predefined Constants and define().

Also consider using set_include_path() and spl_autoload_register().

Happy coding!

Upvotes: 0

ciruvan
ciruvan

Reputation: 5213

Well, there's the DIRECTORY_SEPARATOR constant in PHP, but it's not necessary to use it. If you use forward slashes, you'll be fine in all cases. Windows won't mind.

Upvotes: 3

Related Questions