Jamie February 2016

php does not import variables from another file

I'm working on a cloud system with login/register system and mysql, but the problem is that php does not imports the variables i'm including.

Here is my config file:

<?php
// Connection details
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
 ?> 

And my code to include the config file:

require("/classes/config.class.php");

When i'm trying do echo the variables that are defined in the config it gives this error:

Notice: Undefined variable: servername in C:\xampp\htdocs\index.php on line 2

I'm using xampp on my local computer it has php Version 5.5.30.

EDIT: First lines of php, from comment

<?php 
// Include classes require("/classes/user.class.php"); 
require("/classes/password.class.php"); 
// Include configuration require("/classes/config.class.php"); 
echo $servername; echo $username; echo $password; echo $dbname;

Answers


DurtyFree February 2016

You should check if you are trying to use the variables before including it.

Also check if the file is correctly included ( require(); in php tags and not out commented ( //require ))


fusion3k February 2016

I write an answer because I can't type carriage returns in comments.

Your code in index.php (as your comment above):

<?php // Include classes require("/classes/user.class.php"); require("/classes/password.class.php"); // Include configuration require("/classes/config.class.php");
echo $servername;
(...)

Double slashes // are a comment sign, meaning that all following text it in the same line will be ignored.

I suggest you (also for better code clarity) to edit in this way:

<?php
    // Include classes 
    require("/classes/user.class.php");
    require("/classes/password.class.php");
    // Include configuration 
    require("/classes/config.class.php");

    echo $servername;
    (...)


Bonsai February 2016

If this is not working, you might be just in the wrong scope.

It could be that your include is inside a function, then you need to change the setting of your variables to:

$GLOBALS['servername'] = 'localhost';

or you are using the variable inside a function/class. Then you have to use the global keyword

myFunction() {
  //$servername is not defined here
  global $servername;
  // now $servername is defined and the global var is used
}

But I think you should do something much more usefull: Using Constants.

define('SERVERNAME','localhost');

And later get the constant (In ANY scope):

echo SERVERNAME;


Kyle E4K February 2016

Config.php File:

$database_host = "host";
$database_user = "user";
$database_pass = "pass";
$database_name = "name";

Other file you want to call the Config variables from:

require_once 'Config.php';
$db = mysqli_connect($database_host, $database_user, $database_pass, $database_name);

Post Status

Asked in February 2016
Viewed 1,715 times
Voted 10
Answered 4 times

Search




Leave an answer