1

I'm working on a back office from scratch, and here are some folder examples

Admin > include > global_variable.php

Admin > sliders > variable.php

Admin > sliders > uploadfunction > index.php

In the index.php I have

<?php include('../variable.php'); ?>

And in the variable.php I have

<?php include('../include/global_variable.php');?>

However index.php is not reading the global_variable.php

It gives me the below error

"Warning: include(../include/global_variable.php): failed to open stream: No such file or directory in [irrelevant]\Admin\sliders\variable.php on line <i>1</i>"

No, this isn't an issue with forward-slash and back-slash, because it was working on a different architecture (I was linking ../variable.php and ../../include/global_variable.php on my index.php)

Logically this should work, however it's not. My assumption is that it is reading "../include/global_variable.php" from the directory of the index.php (which it should be reading from the variable.php)

Is there any workaround to it while keeping the same file structures?

Thank you

Patrick Younes
  • 139
  • 1
  • 15
  • I had the same kind of problem. try to check this [link](https://stackoverflow.com/questions/5364233/php-fatal-error-failed-opening-required-file). Also maybe you can check how to use `__DIR__` (useful for deployment) – Lilian Barraud Mar 29 '18 at 10:08
  • Possible duplicate of [include(): Failed to open stream: No such file or directory](https://stackoverflow.com/questions/9557945/include-failed-to-open-stream-no-such-file-or-directory) – Darshan Jain Mar 29 '18 at 10:10
  • Thank you @LilianBarraud This was useful! – Patrick Younes Mar 29 '18 at 10:50

1 Answers1

2

You have a relative path issue.

When including PHP files the path used is relative to the script being executed (not the included one).

So in your case you are including a file from Admin/sliders/uploadfunction, so this is your "base path". Then:

  • ../variable.php is looked for into the sliders directory.
  • ../include/global_variable.php is looked for into the sliders directory.

As posted in comments, try to use the constant __DIR__ in the variable.php include:

<?php include(__DIR__.'/../include/global_variable.php');?>

More about PHP constants: http://php.net/manual/en/language.constants.predefined.php

More about relative path issue: http://yagudaev.com/posts/resolving-php-relative-path-problem/

Pep Lainez
  • 949
  • 7
  • 12