0

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?

3
  • 5
    you can just use / throughout, it will be interpreted correctly on windows machines Commented Jul 30, 2013 at 15:00
  • 1
    Agree with @Orangepill - Forward slashes should work fine on both windows and *nix systems. Commented Jul 30, 2013 at 15:01
  • 2
    PHP will auto-translate directory separators for you. Just use / and don't worry about it. The only thing you'd have to worry about is referring to different drives. Windows'd need D:/, C:/, etc... whereas unix-ish systems couldn't care less about that sort of thing. Commented Jul 30, 2013 at 15:01

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.