views:

77

answers:

2

I have the following files structure:

temp
    main
        index.php
    a.php
    b.php

Here are the files;

index.php

echo "index.php ---> " . __DIR__ . "<br />";

require('../a.php');

echo "OK<br />"

a.php

echo "a.php ---> " . __DIR__ . "<br />";

require('./b.php');

echo "a is here<br />"

b.php

echo "b is here<br />"

When index.php is called I got the following error:

index.php ---> D:\Programs\WampServer 2\www\temp\main
a.php ---> D:\Programs\WampServer 2\www\temp

Warning: require(./b.php) [function.require]: failed to open stream: No such file or directory in D:\Programs\WampServer 2\www\temp\a.php on line 5

Fatal error: require() [function.require]: Failed opening required './b.php' (include_path='.;C:\php5\pear') in D:\Programs\WampServer 2\www\temp\a.php on line 5

I have noticed that if I change

require('./b.php');

to

require('b.php');

Why is that ? it works as expected.

A: 

Use require('..\a.php');

The PHP manual says include uses backslashes for Windows.

Edit:

Oops. I misread the code. Disregard this answer.

willell
Including `a.php` seems to work, there is no error regarding this!
Felix Kling
-1: Slashes are also supported for cross-platform compatibility, as stated in the manual.
Andrew Moore
No it doesn't. To be completely portable, you should use the `DIRECTORY_SEPARATOR` constant though either forward or backward slashes will work on Windows.
Phil Brown
@Phil - PHP's own developers discourage the use of DIRECTORY_SEPARATOR.
mellowsoon
@Phil Brown: PHP's core developers discourage the use of `DIRECTORY_SEPARATOR` and recommend using a forward slash `/`. Also, yes, forward slashes are supported in Windows, see [this manual page](http://php.net/manual/en/function.basename.php).
Andrew Moore
I was simply taking a very pragmatic approach. DIRECTORY_SEPARATOR is also a hideously long constant name for what is only going to be a single character. The only reason to ever use it would be if a system did not support forward slash. To date, no system capable of running PHP exists AFAIK.
Phil Brown
+6  A: 

When you use include or require, the file that you include will act as if it is part of the script that included it. In this case, the file a.php might live in the same directory as b.php, but when the code is running, it is running in the context of index.php. If you had used __FILE__ rather than __DIR__, you would see that a.php returns the same value as index.php when it is running as an included file on index.php.

Since the relative path changes depending on where files are used, it's always best to use an absolute path relative to the server root. If the machine is configured normally, that will start with $_SERVER["DOCUMENT_ROOT"], then add the application path and the includes path. On some shared hosting servers, you might have to hard-code the root somewhere (or add it to the .htaccess file).

Stan Rogers
Thanks a lot !!
Misha Moroshko