1

So recently I decided to move my php code that was at the top of every page, and exactly the same to it's own php file. First thing I did before trying a require_once() on it was to make sure php could read the file so I did

<?php
    if(file_exists('Backend.php')) {
        echo 'File does exist';
    }
?>

And it echo'd out that the file exists perfectly fine. Now whenever i try:

<?php
    require('Backend.php') or die('Could not load Backend.');
?>

I get the error:

 'Warning: require(1): failed to open stream: No such file or directory in
  C:\Users\Owner\Dropbox\PotateOS\index.php on line 2

  Fatal error: require(): Failed opening required '1'(include_path='.;C:\xampp\php\PEAR;C:\Users\Owner\Dropbox\PotateOS') in C:\Users\Owner\Dropbox\PotateOS\index.php on line 2

Note I am using(XAMPP). Things I have tried:

Adding the path of the files to php.ini's include_path

Checking the filename to make sure it doesn't have any strange charectars

Using this as the file path:

<?php
    require($_SERVER['DOCUMENT_ROOT'] . 'Backend.php') or die('Could not load');
?>

(Note both the page i'm trying to access backend from, and backend are in the root directory)

MrRevolutionz
  • 11
  • 1
  • 2

2 Answers2

9

The problem is that require is not a function but a language construct; as a consequence it will run your code as:

require('Backend.php' or die('Could not load Backend.'));

The expression 'Backend.php' or die('Could not load Backend.') yields bool(true) and cast to a string it becomes string(1) "1" and that will be attempted to load.

You can simply reduce your code to this:

require 'Backend.php';

It will raise an error if the file could not be found anyway and will halt the script. As mentioned in the comments, it's important to realise that the document root doesn't have a trailing slash; thus, you must add it yourself:

require $_SERVER['DOCUMENT_ROOT'] . '/Backend.php';
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Perfect explanation! ;) – ek9 May 03 '14 at 14:08
  • That was a mistyping on my part when copying from the file the actual line is: "require('Backend.php') or die('Could not load Backend.');" Thank you though – MrRevolutionz May 03 '14 at 14:34
  • @MrRevolutionz My answer doesn't assert that you've made a typo, because you didn't; is there something else unclear? – Ja͢ck May 05 '14 at 01:53
0

Before require add:

echo getcwd();

and then check if Backend.php is in the same directory as result of this function

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291