25

Structure of my files is like so:

config.php
script
|--myscript.php

myscript.php

<?php
require '../config.php';
?>

When executing php /path/to/myscript.php I get Warning: require(../config.php): failed to open stream: No such file or directory.

Whats the reason?

2
  • Try it with an absolute path, instead of a relative one. Commented Sep 11, 2012 at 20:53
  • yep, im very disappointed now. Commented Sep 11, 2012 at 20:56

5 Answers 5

28

That's because your current working directory is the one you call your command at, not the one your script is located in.

Use

require __DIR__ . '/../config.php';

instead. __DIR__ is a const that points to the directory current file is located in.

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

Comments

8

One way I do it, is like this:

php -d include_path=/path/to/config.php script.php

-d is used to set INI directives at runtime, so you don't have any changing code/configs/directories.

Comments

2

If you don't want to (or can't) change the require line in your code, just cd to the directory that your script expects to be executed within before running your script:

cd /path/to
php /path/to/myscript.php

Comments

2

You need to use absolute path or change working directory:

chdir(dirname(__FILE__));

Comments

1

Most likely you got wrong working directory so your relative paths is not pointing where you expect it to. To see how PHP sees it add:

echo getcwd();

as the 1st line of your script.

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.