PHP Cannot access variable from another php file in another directory

Viewed 782

in /var/www/ is my main.php file:

<?php
include("../config/config.php");
header('Content-type: text/plain');
echo $user;
?>

in /var/config/ is my config.php file

<?php
$user = "myUser";
?>

When calling main.php in my browser I'm getting a blank site, instead of "myUser".

2 Answers

If your document root is set to "/var/www/" then you should work in that directory.

Your code does not work properly because of the "/", on Windows it doesn't matter but on Linux it does and it's different.

Anyway, a more better example would be this:

<?php
include("..".DIRECTORY_SEPARATOR."config".DIRECTORY_SEPARATOR."config.php");
header('Content-type: text/plain');
echo $user;
?>

And now main.php will be able to access your config.php on any operating system.

This worked for me!

include dirname(__FILE__).'/../config/config.php';
Related