문제

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.

도움이 되었습니까?

해결책

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).

다른 팁

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

The PHP manual says include uses backslashes for Windows.

Edit:

Oops. I misread the code. Disregard this answer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top